Android四大组件之——Activity的开启:StartActivity()和StartActivityForResult()(图文详解)

     

      如需转载请在文章开头处注明本博客网址:http://www.cnblogs.com/JohnTsai

      联系方式:JohnTsai.Work@gmail.com

 

      [Android四大组件学习系列Activity篇]

       1.Android四大组件之——Activity(一)定义、状态和后退栈(图文详解)

       2.Android四大组件之——Activity的生命周期(图文详解)

       3.Android四大组件之——Activity的开启StartActivity()和StartActivityForResult()(图文详解)

      前两次学习了Activity的基本概念和生命周期,今天学习一下Activity的跳转和值传递。

      废话不多说,开始学习!

  • Activity的开启

       开启一个新的Activity有两种方法:

                          startActivity(Intent)startActivityForResult(Intent,int)

 

      startActivity(Intent):

                        用于开启一个新的Activity,新Activity压入栈顶。参数Intent用于描述新Activity。

      startActivityForResult(Intent,int):

                        用于开启新Activity,新Activity退出后,返回结果给旧Activity。 

     startActivity好理解,startActivityForResult()就麻烦一点,下面这张图方便我们的理解:

     

          说明一下:

               requestCode,请求码,自己随意设置,但必须是非负数。只有是非负数时,Activity退出时,这个码会返回到onActivityResult()。

               resultCode,结果码,用于标识返回数据来自于哪个新Activity,它的值一般是

               RESULT_CANCELED, RESULT_OK, RESULT_FIRST_USER。

          写了一个关于开启Activity的Demo:

          共三个Activity:MainActivity用户填写用户姓名电话城市、CityActivity用于用户选择城市,ShowActivity用于展示用户信息。

          MainActivity:

 1 package com.johntsai.startactivity;
 2 
 3 import android.app.Activity;
 4 import android.content.Intent;
 5 import android.database.Cursor;
 6 import android.net.Uri;
 7 import android.os.Bundle;
 8 import android.provider.ContactsContract.CommonDataKinds.Phone;
 9 import android.view.View;
10 import android.view.View.OnClickListener;
11 import android.widget.Button;
12 import android.widget.EditText;
13 
14 public class MainActivity extends Activity implements OnClickListener {
15    
16     private Button button_city,button_phone,button_save;
17     private EditText editText_city,editText_name,editText_phone;
18     private static final int SELECT_CITY_REQUEST =2;
19     private static final int SELECT_PHONE_REQUEST =3;
20     
21     @Override
22     protected void onCreate(Bundle savedInstanceState) {
23         super.onCreate(savedInstanceState);
24         setContentView(R.layout.activity_main);
25         
26        button_city = (Button)findViewById(R.id.button_city);
27        button_phone = (Button)findViewById(R.id.button_phone);
28        button_save = (Button)findViewById(R.id.button_save);
29        editText_city = (EditText)findViewById(R.id.editText_city);
30        editText_name = (EditText)findViewById(R.id.editText_name);
31        editText_phone = (EditText)findViewById(R.id.editText_Phone);
32        
33        button_city.setOnClickListener(this);
34        button_phone.setOnClickListener(this);
35        button_save.setOnClickListener(this);
36     }
37     @Override
38     public void onClick(View v) {
39          switch (v.getId()) {
40         case R.id.button_city:
41             Intent i = new Intent ();
42             i.setClass(MainActivity.this, CityActivity.class);
43             startActivityForResult(i, SELECT_CITY_REQUEST);
44             break;
45         case R.id.button_phone:
46              Intent pickContactIntent = new Intent(Intent.ACTION_PICK, Uri.parse("content://contacts"));
47              pickContactIntent.setType(Phone.CONTENT_TYPE);
48              startActivityForResult(pickContactIntent, SELECT_PHONE_REQUEST);
49             break;
50         case R.id.button_save:
51             String name=editText_name.getText().toString();
52             String city = editText_city.getText().toString();
53             String phone = editText_phone.getText().toString();
54             Intent saveIntent = new Intent(MainActivity.this,ShowActivity.class);
55             saveIntent.putExtra("content", "NAME: "+name+"\nCITY:   "+city+"\nPHONE"+phone);
56             startActivity(saveIntent);
57             break;
58         default:
59             break;
60         }        
61     }
62     
63     @Override
64     protected void onActivityResult(int requestCode, int resultCode, Intent data) {
65         if(SELECT_CITY_REQUEST == requestCode){
66             if(resultCode ==RESULT_OK){
67                 String city = data.getStringExtra("city");
68                 editText_city.setText(city);
69             }
70         }
71         if(SELECT_PHONE_REQUEST == requestCode){
72             if(resultCode == RESULT_OK){
73                  Uri contactData = data.getData();
74                  String [] projection ={Phone.NUMBER};
75                  Cursor c = getContentResolver()
76                          .query(contactData, projection, null, null, null);
77                  c.moveToFirst();
78                  int column =c.getColumnIndex(Phone.NUMBER);
79                  String num = c.getString(column);  
80                  editText_phone.setText(num);
81             }
82         }
83         super.onActivityResult(requestCode, resultCode, data);
84     }
85 }
  1 package com.johntsai.startactivity;
  2 
  3 
  4 import android.app.Activity;
  5 import android.content.Intent;
  6 import android.os.Bundle;
  7 import android.view.Gravity;
  8 import android.view.View;
  9 import android.view.ViewGroup;
 10 import android.widget.AbsListView;
 11 import android.widget.BaseExpandableListAdapter;
 12 import android.widget.ExpandableListAdapter;
 13 import android.widget.ExpandableListView;
 14 import android.widget.LinearLayout;
 15 import android.widget.TextView;
 16 import android.widget.Toast;
 17 
 18 public class CityActivity extends Activity {
 19     
 20      private     ExpandableListView eListView;
 21     @Override
 22     protected void onCreate(Bundle savedInstanceState) {
 23       
 24          super.onCreate(savedInstanceState);
 25          setContentView(R.layout.layout_city);
 26          initEListView();
 27     }
 28      
 29      //初始化
 30      private void initEListView(){
 31             ExpandableListAdapter adapter = new BaseExpandableListAdapter() {
 32                 
 33        
 34                 private String [] countries = new String[]{
 35                         "China","USA","UK"
 36                 };
 37                 
 38                 private String [][] cities = new String[][]{
 39                         {"BeiJing","ShangHai","HongKong","TaiBei"},
 40                         {"Washington","New York","Los Angles","San Fransico"},
 41                         {"London","Manchester","Birmingham","Liverpool"}
 42                 };
 43                 private TextView getTextView(){
 44                     AbsListView.LayoutParams lp = new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
 45                             ViewGroup.LayoutParams.WRAP_CONTENT);
 46                     TextView textView = new TextView(CityActivity.this);
 47                     textView.setLayoutParams(lp);
 48                     textView.setGravity(Gravity.CENTER_HORIZONTAL);
 49                     textView.setPadding(0, 0, 0, 0);
 50                     textView.setTextSize(20);
 51                     return textView;
 52                     
 53                 }
 54                 @Override
 55                 public boolean isChildSelectable(int groupPosition, int childPosition) {
 56                     Toast.makeText(CityActivity.this, "you have clicked Group:"+groupPosition+"Child:"+childPosition+"\n"+countries[groupPosition]+"  "+cities[groupPosition][childPosition], 
 57                             Toast.LENGTH_SHORT).show();
 58                     Intent i = new Intent();
 59                     i.putExtra("city", cities[groupPosition][childPosition]);
 60                     setResult(RESULT_OK, i);
 61                     finish();
 62                     return true;
 63                 } 
 64                 
 65                 @Override
 66                 public boolean hasStableIds() {
 67                     return true;
 68                 }
 69                 
 70                 @Override
 71                 public View getGroupView(int groupPosition, boolean isExpanded,
 72                         View convertView, ViewGroup parent) {
 73                     LinearLayout linearLayout = new LinearLayout(CityActivity.this);
 74                     linearLayout.setOrientation(0);
 75                     
 76                     TextView textView = getTextView();
 77                     textView.setText(getGroup(groupPosition).toString());
 78                     linearLayout.addView(textView);
 79                     return linearLayout;
 80                 }
 81                 @Override
 82                 public long getGroupId(int groupPosition) {
 83                     return groupPosition;
 84                 }
 85                 
 86                 @Override
 87                 public int getGroupCount() {
 88                     return countries.length;
 89                 }
 90                 
 91                 @Override
 92                 public Object getGroup(int groupPosition) {
 93                     return countries[groupPosition];
 94                 }
 95                 
 96                 @Override
 97                 public int getChildrenCount(int groupPosition) {
 98                     return cities[groupPosition].length;
 99                 }
100                 
101                 @Override
102                 public View getChildView(int groupPosition, int childPosition,
103                         boolean isLastChild, View convertView, ViewGroup parent) {
104                      TextView textView = getTextView();
105                      textView.setText(getChild(groupPosition, childPosition).toString());
106                      textView.setGravity(Gravity.CENTER_HORIZONTAL);
107                      return textView;
108                 }
109                 
110                 @Override
111                 public long getChildId(int groupPosition, int childPosition) {
112                       return childPosition;
113                 }
114                 
115                 @Override
116                 public Object getChild(int groupPosition, int childPosition) {
117                     return cities[groupPosition][childPosition];
118                 }
119             };
120              eListView = (ExpandableListView)findViewById(R.id.expandableListView);
121              eListView.setAdapter(adapter);
122      }
123 }
CityActivity
 1 package com.johntsai.startactivity;
 2 
 3 import android.app.Activity;
 4 import android.content.Intent;
 5 import android.os.Bundle;
 6 import android.widget.TextView;
 7 
 8 public class ShowActivity extends Activity {
 9     private TextView showTextView;
10     @Override
11     protected void onCreate(Bundle savedInstanceState) {
12          super.onCreate(savedInstanceState);
13          setContentView(R.layout.layout_show);
14          showTextView = (TextView)findViewById(R.id.textView_show);
15          
16          Intent i =getIntent();
17          String content = i.getStringExtra("content");
18          showTextView.setText(content);
19     }
20 }
ShowActivity

Demo运行效果图

 

                      

 

 

 

                        

 如果喜欢,请推荐!谢谢~

posted @ 2014-10-28 23:28  onerepublic  阅读(3895)  评论(0编辑  收藏  举报