美文网首页
startActivityForResult

startActivityForResult

作者: lucas777 | 来源:发表于2022-04-04 21:33 被阅读0次

通过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);
    }
}

相关文章

网友评论

      本文标题:startActivityForResult

      本文链接:https://www.haomeiwen.com/subject/efkhsrtx.html