Androidstudio's intent summary (2)

PS: Overview of layout connection to AndroidStudio (1)

Passing data to the next activity:
After the study of the previous sections, you already have a certain understanding of Intent. But so far, we have simply
used Intent to start an activity. In fact, Intent can also pass data when starting an activity. Let's take a
look.
The idea of ​​passing data when starting an activity is very simple. Intent provides a series of overloads of the putExtra() method, which
can temporarily store the data we want to pass in the Intent. After starting another activity, we only need to put these The data can then be taken out from the Intent
. For example, there is no string in MainActiviy, and now you want to pass this character car to Main2
Activity, you can write:
button.setOnClickListener(new View.OnClickListener0 ) { @Override public void onClick (View v) { String data = "Hello Main2Activity" Intent intent = new Intent (MainActivity.this, Main2Activity.class): intent.putExtra ("extra_data", data); startActivity(intent): } )); Here we still use explicit Intent to start Main2Activicy, and passed the putExtra() method









- a string. Note that the putExtra() method here receives two parameters, the first parameter is the key, which is used to retrieve the
value from the Intent later, and the second parameter is the actual data to be passed.
Then we take out the passed data in Main2Acrivity and print it out, the code is as follows

package com.example.firstcode;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

public class Main2Activity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        Intent intent=getIntent();
        String data=intent.getStringExtra("extra_data");
        Log.d("Main2Activity", data );
    }
}

First, you can get the Intent used to start SecondActivity through the getIntent() method, then call the
getstring Extra() method, pass the corresponding key value, and then you can get the passed data. Here, since we are passing a
string of characters, we use the getstringExtra() method to get the transmitted data. If the integer data is passed,
use the getIntExtra() method; if the Boolean data is passed, use the getBooleanExtra() method, and so
on.
Re-run the program, click the button on the FirstActivity interface to jump to SecondActivity, check the logcat to see that Main2Activity successfully received the signal data from MainActivity

 

Guess you like

Origin blog.csdn.net/Abtxr/article/details/124028643