对startActivityForResult理解,通过简单例子有了浅的理解,通过他可以实现两个activity之间相互传递数据。
MainActivity和TwoActivity之间传递数据,并修改UI,在TwoActivity中使用handler处理Intent,在MainActivity中onActivityResult中修改UI界面,这样可以实现,
public class MainActivity extends Activity {
private TextView tv_text;
private Button bt_change;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv_text = (TextView) findViewById(R.id.tv_text);
bt_change = (Button) findViewById(R.id.bt_change);
bt_change.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), TwoActivity.class);
startActivityForResult(intent, 0);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
Bundle extras = data.getExtras();
String string = extras.getString("value");
System.out.println("接收到:"+string);
tv_text.setText(string);
bt_change.setVisibility(View.GONE);
}
}
public class TwoActivity extends Activity {
private MainHandler handler;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_two);
Button bt_send = (Button) findViewById(R.id.bt_send);
handler = new MainHandler();
onClick(bt_send);
}
class MainHandler extends Handler{
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
switch (msg.what) {
case 0:
Intent intent = getIntent();
Bundle bundle = new Bundle();
bundle.putString("value", "我来了");
Intent extras = intent.putExtras(bundle);
TwoActivity.this.setResult(0, extras);
TwoActivity.this.finish();
break;
default:
break;
}
}
}
private void onClick(Button bt_send) {
bt_send.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
handler.sendEmptyMessageDelayed(0, 1000);
}
});
}
}
在TwoActivity中通过getIntent()方法获取上一个activity传过来的intent,在这个intent设置数据,在setResult()方法中加入数据,这样就可以在onActivityResult()中接收数据了。
以上只是我这个菜鸟平时学习的一些总结,若是有不对的地方和不足之处请多多指教。