如何使用 Intent 和 OnActivityResult 传递内容?

How can I pass content using Intent and OnActivityResult?

我的问题是:

我有2个类:

当我在 FirstActivity 上单击 fab button 时,我想将 String variable 传递给 SecondActivity 并转到 SecondActivity。在 SecondActivity 中,我将收到该字符串并对其进行 Toast。

我该怎么做? 非常感谢

将您的代码放入您的 fab 按钮 onClickListener

Intent mIntent = new Intent(mContext, SecondActivity.class);
mIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
mIntent.putExtra("key", "Your value");
startActivity(mIntent);

并在 SecondActivity.java 收到赞

String value = getIntent().getStringArrayExtra("key")

key 是您可以根据需要提供的特定变量的唯一名称。

如果你有传递变量,那么简单地把你的变量像

String str = "This is my meesage";
mIntent.putExtra("key", str);

在你的 fab buttons onClick 方法中

//creating and initializing an Intent object
Intent intent = new Intent(this, SecondActivity.class);

//attach the key value pair using putExtra to this intent
String user_name = "Jhon Doe";
intent.putExtra("USER_NAME", user_name);

//starting the activity
startActivity(intent);

在你的 SecondActivity onCreate 方法中

//get the current intent
Intent intent = getIntent();

//get the attached extras from the intent
//we should use the same key as we used to attach the data.
String user_name = intent.getStringExtra("USER_NAME");

来源:https://zocada.com/using-intents-extras-pass-data-activities-android-beginners-guide/