在startActivity()中传递Bundle?

190

如何正确地将Bundle传递给从当前活动启动的活动?共享属性?

5个回答

467
你有几个选项:
1)使用来自意图(Intent)的Bundle:从Intent获取Bundle
1)使用来自 Intent 的 Bundle:从 Intent 获取 Bundle 。
Intent mIntent = new Intent(this, Example.class);
Bundle extras = mIntent.getExtras();
extras.putString(key, value);  

2) 创建一个新的 Bundle

Intent mIntent = new Intent(this, Example.class);
Bundle mBundle = new Bundle();
mBundle.putString(key, value);
mIntent.putExtras(mBundle);

3) 使用 Intent 的 putExtra() 快捷方法

Intent mIntent = new Intent(this, Example.class);
mIntent.putExtra(key, value);
然后,在启动的 Activity 中,您可以通过以下方式读取它们:
String value = getIntent().getExtras().getString(key)

注意:Bundle类提供了所有基本类型、可序列化对象和Parcelable接口的“get”和“put”方法。我仅出于示例目的使用了字符串。


21
您可以使用Intent中的Bundle:

您可以使用Intent中的Bundle:

Bundle extras = myIntent.getExtras();
extras.put*(info);

或者整个捆绑包:

myIntent.putExtras(myBundle);

这是您要找的内容吗?


1
从生成的意图中,您调用getIntent().getExtras().get*()来获取之前存储的内容。 - yanchenko

17

在Android中将数据从一个Activity传递到另一个Activity

Intent包含操作和可选的附加数据。可以使用Intent的putExtra()方法将数据传递给其他Activity。数据作为额外信息(extras)传递,并以键值对的形式存在。键始终是字符串类型,而值可以使用基本数据类型,如int、float、char等。我们还可以在活动之间传递可序列化(Serializable)和可解组合(Parcelable)对象。

Intent intent = new Intent(context, YourActivity.class);
intent.putExtra(KEY, <your value here>);
startActivity(intent);

从Android活动中检索包数据

您可以使用Intent对象上的getData()方法检索信息。Intent对象可以通过getIntent()方法检索。

 Intent intent = getIntent();
  if (null != intent) { //Null Checking
    String StrData= intent.getStringExtra(KEY);
    int NoOfData = intent.getIntExtra(KEY, defaultValue);
    boolean booleanData = intent.getBooleanExtra(KEY, defaultValue);
    char charData = intent.getCharExtra(KEY, defaultValue); 
  }

7

您可以使用 Bundle 将值从一个活动传递到另一个活动。在当前活动中,创建一个 bundle,并将 bundle 设置为特定的值,然后将该 bundle 传递给 intent。

Intent intent = new Intent(this,NewActivity.class);
Bundle bundle = new Bundle();
bundle.putString(key,value);
intent.putExtras(bundle);
startActivity(intent);

现在在你的NewActivity中,你可以获取这个Bundle并检索你的值。

Bundle bundle = getArguments();
String value = bundle.getString(key);

您可以通过意图传递数据。在当前活动中,设置意图如下:
Intent intent = new Intent(this,NewActivity.class);
intent.putExtra(key,value);
startActivity(intent);

现在在你的NewActivity中,你可以像这样从intent中获取那个值:

String value = getIntent().getExtras().getString(key);

为什么要使用Bundle,而Intent对象有getExtra和putExtra方法? - Psychosis404

3

请写下您正在进行的活动:

Intent intent = new Intent(CurrentActivity.this,NextActivity.class);
intent.putExtras("string_name","string_to_pass");
startActivity(intent);

在NextActivity.java中。
Intent getIntent = getIntent();
//call a TextView object to set the string to
TextView text = (TextView)findViewById(R.id.textview_id);
text.setText(getIntent.getStringExtra("string_name"));

这个对我有效,你可以试一下。
来源:https://www.c-sharpcorner.com/article/how-to-send-the-data-one-activity-to-another-activity-in-android-application/

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接