Android 如何通过向 Intent 传递一些参数来启动它?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2405120/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 05:43:48  来源:igfitidea点击:

How to start an Intent by passing some parameters to it?

androidconstructorandroid-intent

提问by Pentium10

I would like to pass some variables in the constructor of my ListActivity

我想在 ListActivity 的构造函数中传递一些变量

I start activity via this code:

我通过以下代码开始活动:

startActivity(new Intent (this, viewContacts.class));

I would like to use similar code, but to pass two strings to the constructor. How is possible?

我想使用类似的代码,但将两个字符串传递给构造函数。怎么可能?

回答by Xitcod13

In order to pass the parameters you create new intent and put a parameter map:

为了传递参数,您创建新意图并放置参数映射:

Intent myIntent = new Intent(this, NewActivityClassName.class);
myIntent.putExtra("firstKeyName","FirstKeyValue");
myIntent.putExtra("secondKeyName","SecondKeyValue");
startActivity(myIntent);

In order to get the parameters values inside the started activity, you must call the get[type]Extra()on the same intent:

为了在启动的活动中获取参数值,您必须get[type]Extra()在相同的意图上调用:

// getIntent() is a method from the started activity
Intent myIntent = getIntent(); // gets the previously created intent
String firstKeyName = myIntent.getStringExtra("firstKeyName"); // will return "FirstKeyValue"
String secondKeyName= myIntent.getStringExtra("secondKeyName"); // will return "SecondKeyValue"

If your parameters are ints you would use getIntExtra()instead etc. Now you can use your parameters like you normally would.

如果您的参数是整数,您将使用getIntExtra()等。现在您可以像往常一样使用您的参数。

回答by RickNotFred

I think you want something like this:

我想你想要这样的东西:

Intent foo = new Intent(this, viewContacts.class);
foo.putExtra("myFirstKey", "myFirstValue");
foo.putExtra("mySecondKey", "mySecondValue");
startActivity(foo);

or you can combine them into a bundle first. Corresponding getExtra() routines exist for the other side. See the intent topicin the dev guide for more information.

或者您可以先将它们组合成一个包。另一侧存在相应的 getExtra() 例程。有关更多信息,请参阅开发指南中的意图主题