Use intent to return data to explain the previous activity instance (use onBackPressed() to return data to solve the problem of the previous activity)

1. Add controls to the layout of FirstActivity:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.firstactivitya.FirstActivity">

    <Button
        android:id="@+id/goto_second_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="to SecondActivity"/>

</LinearLayout>
2. Modify the code in FirstActivity:
public class FirstActivity extends AppCompatActivity {

    private Button gotoSecondBtn;
    private static  final String TAG = "FirstActivity";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_first);

        gotoSecondBtn = findViewById(R.id.goto_second_btn);
        //对按钮进行监听
        gotoSecondBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //使用intent进行跳转
                Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
                //启动跳转,这里使用startActivityForResult()方法,这个方法会在跳转到的活动页面销毁时,返回一个数据给上一个活动
                /**
                 * param1:intent
                 * param2:请求码,用于回调时判断数据的来源
                 */
                startActivityForResult(intent, 1);
            }
        });
    }
}
3. Send a message in SecondActivity:
public class SecondActivity extends AppCompatActivity {

    private Button secondBtn;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        secondBtn = findViewById(R.id.second_btn);
        secondBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //创建Intent对象
                Intent intent = new Intent();
                //通过put()以键值对的方式赋值
                intent.putExtra("hi", "hi FirstActivity");
                //通过setResult()方法向上一个活动返回结果 param1:处理结果代号
                setResult(1, intent);
                finish();
            }
        });
    }
    }
4. Finally, overwrite onActivityResult() in FirstActivity to receive the message:
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.e(TAG, "onActivityResult1: "+data );
        switch (resultCode) {
            //下面的1为startActivityForResult(intent, 1);中的1
            case 1:
                //这里的1为setResult(1, intent);中的1
                if (resultCode==1){
                    String str = data.getStringExtra("hello");
                    Log.e(TAG, "onActivityResult2: "+str );
                    String str2 = data.getStringExtra("hi");
                    Log.e(TAG, "onActivityResult3: "+str2 );
                }
                break;


            default:
                break;

        }
    }
}
OK, so you can pass the value, but you may have to ask again, where does String str = data.getStringExtra("hello"); come from, this is the code I will write below, and add it in SecondActivity:
    @Override
    public void onBackPressed() {
//        super.onBackPressed();
        Intent intent = new Intent();
        intent.putExtra("hello","Hello FirstActivity");
        setResult(1,intent);
        finish();
    }
It is possible to return the data without clicking the button but clicking the return key. If you look at my code carefully, you can see that I have commented out // super.onBackPressed(); because if it is not commented, it will call The default processing method of onBackPressed() cannot implement returning data to the previous activity. This is a mistake I made. Of course, the previous method can be used to monitor the back button:
 @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent();
            intent.putExtra("hello", "Hello FirstActivity");
            setResult(1, intent);
            finish();
        }
        return super.onKeyDown(keyCode, event);

    }

Finally, you can look at the operation effect:
write picture description here

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325541845&siteId=291194637