通过startActivityForResult跳转Activity时,可以从跳转的Activity拿到数据返回
代码如下:
MainActivity.java
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//跳转到第二个页面
public void toSecond(View v ){
Intent intent = new Intent(this, SecondActivity.class);
startActivityForResult(intent, 0);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
String result = data.getExtras().getString("result");
Toast.makeText(this, "返回来的数据为:"+result, 1).show();
}
}
SecondActivity.java
public class SecondActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Intent data = new Intent();
data.putExtra("result", "我是obama");
setResult(1,data);
}
}
网友评论