Android中启动其他Activity并返回结果

jopen 10年前

启动其他Activity的一种常用方式就是StartActivity(),但有时候我们期望获取指定Activity返回的结果。这时,就需要使用startActivityForResult()方法,为了获取被启动的 Activity所返回的结果,当前Activity需要重写onActivityResult(int requestCode,int resultCode,Intent intent),其中requestCode代表请求码,resultCode代表返回的结果码,它们都是开发者根据业务自行设定的。这样就可以通过请求码和结果码来判断请求是由谁发出的,结果是由谁返回的。下面通过一个实例来演示:

第一个Activity:

 
import android.app.Activity;    import android.content.Intent;    import android.os.Bundle;    import android.view.View;    import android.view.View.OnClickListener;    import android.widget.Button;    import android.widget.EditText;        public class MainActivity extends Activity {        Button btn;        EditText city;            @Override        protected void onCreate(Bundle savedInstanceState) {            super.onCreate(savedInstanceState);            setContentView(R.layout.activity_main);            city = (EditText) findViewById(R.id.activity_main_et);            btn = (Button) findViewById(R.id.activity_main_btn);            btn.setOnClickListener(new OnClickListener() {                    @Override                public void onClick(View v) {                    // 创建需要对应于目标Activity的Intent                    Intent intent = new Intent(MainActivity.this,                            SelectCityActivity.class);                    // 启动指定Activity并等待返回的结果,其中0是请求码,用于标识该请求                    startActivityForResult(intent, 0);                }            });        }            @Override        protected void onActivityResult(int requestCode, int resultCode, Intent data) {            if (requestCode == 0 && resultCode == 0) {                // 取出Intent里的数据                String resultCity = data.getStringExtra("city");                // 修改city文本框的内容                city.setText(resultCity);            }            }    }  


第二个Activity:

 
import android.app.ExpandableListActivity;    import android.content.Intent;    import android.os.Bundle;    import android.view.Gravity;    import android.view.View;    import android.view.ViewGroup;    import android.widget.AbsListView;    import android.widget.BaseExpandableListAdapter;    import android.widget.ExpandableListAdapter;    import android.widget.ExpandableListView;    import android.widget.ExpandableListView.OnChildClickListener;    import android.widget.LinearLayout;    import android.widget.TextView;        public class SelectCityActivity extends ExpandableListActivity {        // 定义省份数组        private String[] provinces = new String[] { "广东", "广西", "湖南", "四川" };        // 定义各省份的城市数组        private String[][] cities = new String[][] { { "广州", "深圳", "珠海", "中山" },                { "桂林", "柳州", "南宁", "北海" }, { "长沙", "岳阳", "衡阳", "株洲" },                { "成都", "绵阳", "广安", "雅安" }, };            @Override        protected void onCreate(Bundle savedInstanceState) {            super.onCreate(savedInstanceState);            // 创建一个可展开的列表组件ExpandableListAdapter对象            ExpandableListAdapter adapter = new BaseExpandableListAdapter() {                @Override                public boolean isChildSelectable(int groupPosition,                        int childPosition) {                        return true;                }                    @Override                public boolean hasStableIds() {                        return true;                }                    // 构建每个父列表组件                @Override                public View getGroupView(int groupPosition, boolean isExpanded,                        View convertView, ViewGroup parent) {                    // 创建一个LinearLayout对象                    LinearLayout ll = new LinearLayout(SelectCityActivity.this);                    ll.setOrientation(0);                    TextView textView = getTextView();                    // 根据groupPosition取provinces对应文本作为textView显示的文本内容                    textView.setText(getGroup(groupPosition).toString());                    ll.addView(textView);                    return ll;                }                    @Override                public long getGroupId(int groupPosition) {                    return groupPosition;                }                    @Override                public int getGroupCount() {                        return provinces.length;                }                    @Override                public Object getGroup(int groupPosition) {                        return provinces[groupPosition];                }                    @Override                public int getChildrenCount(int groupPosition) {                        return cities[groupPosition].length;                }                    /**                * 在MainActivity里创建TextView组件                *                 * @return TextView                */                private TextView getTextView() {                    AbsListView.LayoutParams lp = new AbsListView.LayoutParams(                            ViewGroup.LayoutParams.MATCH_PARENT, 64);                    TextView textView = new TextView(SelectCityActivity.this);                    textView.setLayoutParams(lp);                    textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);                    textView.setPadding(36, 0, 0, 0);                    textView.setTextSize(20);                    return textView;                }                    // 构建子列表的数据                @Override                public View getChildView(int groupPosition, int childPosition,                        boolean isLastChild, View convertView, ViewGroup parent) {                    TextView textView = getTextView();                    // 根据groupPosition和childPosition取cities中对应文本作为textView显示的内容                    textView.setText(getChild(groupPosition, childPosition)                            .toString());                    return textView;                }                    @Override                public long getChildId(int groupPosition, int childPosition) {                        return childPosition;                }                    @Override                public Object getChild(int groupPosition, int childPosition) {                        return cities[groupPosition][childPosition];                }            };            setListAdapter(adapter);            // 为各个子列表绑定事件监听器            this.getExpandableListView().setOnChildClickListener(                    new OnChildClickListener() {                            @Override                        public boolean onChildClick(ExpandableListView parent,                                View v, int groupPosition, int childPosition,                                long id) {                            Intent intent = getIntent();                            Bundle data = new Bundle();                            data.putString("city",                                    cities[groupPosition][childPosition]);                            intent.putExtras(data);                            // 设置该SelectCityActivity结果码,并设置结束之后退回的Activity                            SelectCityActivity.this.setResult(0, intent);                            // 结束SelectCityActivity                            SelectCityActivity.this.finish();                            return false;                        }                    });        }        }