zoukankan      html  css  js  c++  java
  • 在Activity之间传递数据—获取Activity返回的数据

    在获取返回值时要注意的是打开Activity的方式,用方法:startActivityForResult

    接收时,重写方法:onActivityResult
    在子Activity中,写数据用方法:setResult

    MainActivity代码:

     private TextView tv;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
    findViewById(R.id.btnStart).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent i=new Intent(MainActivity.this,OthereActivity.class);
           startActivityForResult(i,0); //用这种方式启动接收 ,第二个为请求码
        }
    });
        }
    
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
    
            tv=(TextView)findViewById(R.id.textView);
    
            tv.setText("另一个Activity返回的是:"+data.getStringExtra("data"));
        }

    OtherActivity代码:
    private EditText editText;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_othere);
    
           editText= (EditText) findViewById(R.id.editText);
            findViewById(R.id.btnBack).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent=new Intent();
                    intent.putExtra("data",editText.getText().toString());
                    setResult(1,intent); //写返回值
                    finish();//结束掉当前Activity
                }
            });
        }
     
  • 相关阅读:
    Maximum Profit Aizu
    Maximum Profit Aizu
    Codeforces Round #552 (Div. 3) —— B. Make Them Equal
    Codeforces Round #552 (Div. 3) —— B. Make Them Equal
    每周一题 —— 3n+1问题
    每周一题 —— 3n+1问题
    Georgia and Bob POJ
    Georgia and Bob POJ
    LeetCode 292. Nim Game
    OpenCV:初试牛刀-带滚动条的视频播放-2
  • 原文地址:https://www.cnblogs.com/hometown/p/4579413.html
Copyright © 2011-2022 走看看