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

时间:2019-06-04 08:17:15

标签: android android-intent onactivityresult

我的问题是:

我有2个课程:

  • FirstActivity.java
  • SecondActivity.java

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

我该怎么做? 非常感谢

2 个答案:

答案 0 :(得分:1)

在您的晶圆厂按钮中,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/

答案 1 :(得分:0)

将此代码放入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);