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

有帮助吗?

解决方案

您有一些选择:

1)使用 来自 意图:

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

2)创建一个新捆绑包

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

3)使用 putextra() 意图的快捷方式

Intent mIntent = new Intent(this, Example.class);
mIntent.putExtra(key, value);


然后,在启动的活动中,您将通过:

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

笔记: 捆绑包具有所有原始类型,包裹和序列化的“获取”和“放置”方法。我只是将字符串用于演示目的。

其他提示

您可以使用意图中的捆绑包:

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

或整个捆绑包:

myIntent.putExtras(myBundle);

这是您想要的吗?

将数据从一个活动传递到Android中的活动

一个意图包含操作和可选的其他数据。数据可以使用意图传递给其他活动 putExtra() 方法。数据作为额外传递,是 key/value pairs. 。钥匙始终是字符串。作为价值,您可以使用原始数据类型int,float,chars等。我们也可以通过 Parceable and Serializable 从一个活动到另一个活动的对象。

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

从Android活动中检索捆绑数据

您可以使用 getData() 意图对象的方法。这 意图 可以通过 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); 
  }

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

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

现在,在您的新功能中,您可以得到此捆绑包并检索您的价值。

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

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

Intent intent = new Intent(this,NewActivity.class);
intent.putExtra(key,value);
startActivity(intent);

现在,在您的新功能中,您可以从这样的意图中获得该价值,

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

写这是您所在的活动:

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-Activity-in-Android-application/

您可以在您的 首次活动 :

 Intent i = new Intent(Context, your second activity.class);
        i.putExtra("key_value", "your object");
        startActivity(i);

并获取对象 第二个活动 :

 Intent in = getIntent();
    Bundle content = in.getExtras();
   // check null
        if (content != null) {
            String content = content_search.getString("key_value"); 
    }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top