在startActivity()上传递一个bundle?

yan*_*nko 162 android bundle android-activity

将捆绑包传递给从当前活动中启动的活动的正确方法是什么?共享属性?

Jer*_*gan 409

你有几个选择:

1)使用意向:

Intent mIntent = new Intent(this, Example.class);
Bundle extras = mIntent.getExtras();
extras.putString(key, value);  
Run Code Online (Sandbox Code Playgroud)

2)创建一个新的Bundle

Intent mIntent = new Intent(this, Example.class);
Bundle mBundle = new Bundle();
mBundle.putString(key, value);
mIntent.putExtras(mBundle);
Run Code Online (Sandbox Code Playgroud)

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

Intent mIntent = new Intent(this, Example.class);
mIntent.putExtra(key, value);
Run Code Online (Sandbox Code Playgroud)


然后,在启动的Activity中,您将通过以下方式阅读它们:

String value = getIntent().getExtras().getString(key)
Run Code Online (Sandbox Code Playgroud)

注意: Bundles对所有基本类型,Parcelables和Serializables都有"get"和"put"方法.我只是将Strings用于演示目的.


Dus*_*inB 18

您可以使用Intent中的Bundle:

Bundle extras = myIntent.getExtras();
extras.put*(info);
Run Code Online (Sandbox Code Playgroud)

或整个捆绑:

myIntent.putExtras(myBundle);
Run Code Online (Sandbox Code Playgroud)

这是你在找什么?


Int*_*iya 13

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

intent包含操作和可选的附加数据.可以使用intent putExtra()方法将数据传递给其他活动.数据作为附加内容传递key/value pairs.密钥始终是String.作为值,您可以使用原始数据类型int,float,chars等.我们还可以将Parceable and Serializable对象从一个活动传递到另一个活动.

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

从android活动中检索包数据

您可以使用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); 
  }
Run Code Online (Sandbox Code Playgroud)


小智 6

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

Intent intent = new Intent(this,NewActivity.class);
Bundle bundle = new Bundle();
bundle.putString(key,value);
intent.putExtras(bundle);
startActivity(intent);
Run Code Online (Sandbox Code Playgroud)

现在在您的 NewActivity 中,您可以获取此包并检索您的值。

Bundle bundle = getArguments();
String value = bundle.getString(key);
Run Code Online (Sandbox Code Playgroud)

您还可以通过意图传递数据。在您当前的活动中,像这样设置意图,

Intent intent = new Intent(this,NewActivity.class);
intent.putExtra(key,value);
startActivity(intent);
Run Code Online (Sandbox Code Playgroud)

现在在您的 NewActivity 中,您可以从这样的意图中获取该值,

String value = getIntent().getExtras().getString(key);
Run Code Online (Sandbox Code Playgroud)