安卓:如何将数据传递给子活动?

11

主活动包含一些具有设定值的变量。我创建了一个子活动,并在表单中填写数据,这些数据必须从主活动传递给子活动以启动。

有人知道如何从主活动将变量值传递到子活动吗?

谢谢!

3个回答

20

你可以在主活动中使用这个方法

Intent i = new Intent(this, YourMainClass.class);
i.putExtra("key", value);

然后在子活动中使用这个方法获取值,通常在onCreate事件中。

int value = getIntent().getExtras().getInt("key");

希望这能帮到你。


2

这个能在主活动中使用吗?

Intent i = new Intent(this, YourMainClass.class);
i.putExtra("key", value);

接下来是:

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

你能添加多个“额外选项”吗?或者类似的东西?
i.putExtra("key", value1); 
i.putExtra("key2", value2);
i.putExtra("key3", value3);

谢谢...


0

试一下这个,它会起作用的:

activity1.class:

Intent i = new Intent(activity1.this,activity2.class);

Bundle b = new Bundle();
b.putString("name", "your value need to pass here");

i.putExtras(b);
startActivity(i);

activity2.class:

Bundle b = this.getIntent().getExtras();

String name = b.getString("name");

((TextView)findViewById(R.id.textView1)).setText(name);

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