一个android应用程序通常含有多个Activity,但只能有一个Activity作为程序的入口,即android应用运行时会自动启动并执行的这个Activity。至于其他的Activity,会被入口Activity调用。
public class ActivityForResult extends Activity
{
Button bn;
EditText city;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//获取界面上的组件
bn = (Button)findViewById(R.id.bn);
city = (EditText)findViewById(R.id.city);
//为按钮绑定事件监听器
bn.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View source)
{
//创建需要对应于目标Activity的Intent
Intent intent = new Intent(ActivityForResult.this
, SelectCityActivity.class);
//启动指定Activity并等待返回的结果,其中0是请求码,用于标识该请求
startActivityForResult(intent , 0);
}
});
}
//重写该方法,该方法以回调的方式来获取指定Activity返回的结果
@Override
public void onActivityResult(int requestCode , int resultCode
, Intent intent)
{
//当requestCode、resultCode同时为0,也就是处理特定的结果
if (requestCode == 0
&& resultCode == 0)
{
//取出Intent里的Extras数据
Bundle data = intent.getExtras();
//取出Bundle中的数据
String resultCity = data.getString("city");
//修改city文本框的内容
city.setText(resultCity);
}
}
}
SelectCityActivity.java
public class SelectCityActivity extends ExpandableListActivity
{
//定义省份数组
private String[] provinces = new String[]
{ "广东", "广西", "湖南"};
private String[][] cities = new String[][]
{
{ "广州", "深圳", "珠海", "中山" },
{ "桂林", "柳州", "南宁", "北海" },
{ "长沙", "岳阳" , "衡阳" , "株洲" }
};
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
ExpandableListAdapter adapter = new BaseExpandableListAdapter()
{……};
// 设置该窗口显示列表
setListAdapter(adapter);
getExpandableListView().setOnChildClickListener(
new OnChildClickListener()
{
@Override
public boolean onChildClick(ExpandableListView parent, View source,
int groupPosition, int childPosition, long id)
{
//获取启动该Activity之前的Activity对应的Intent
Intent intent = getIntent();
Bundle data = new Bundle();
data.putString("city" ,cities[groupPosition][childPosition]);
intent.putExtras(data);
// 设置该SelectActivity的结果码,并设置结束之后退回的Activity
SelectCityActivity.this.setResult(0 , intent);
//结束SelectCityActivity。
SelectCityActivity.this.finish();
return false;
}
});
}
}