【问题标题】:How to start an Intent by passing some parameters to it?如何通过传递一些参数来启动一个 Intent?
【发布时间】:2021-11-26 09:15:04
【问题描述】:

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

我通过此代码开始活动:

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

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

【问题讨论】:

  • 我认为如果它询问如何将参数传递给新的 Activity 以及如何在传递参数后获取参数,这将是一个更好的问题。我不明白如果您需要同时使用这两个问题才能真正拥有任何功能,为什么我们需要有 2 个单独的问题。 (这就是为什么我在下面的答案中包含了如何获取参数)

标签: android constructor android-intent


【解决方案1】:

为了传递参数,你创建新的意图并放置一个参数映射:

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

为了在启动的活动中获取参数值,您必须以相同的意图调用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"

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

【讨论】:

    【解决方案2】:

    我想你想要这样的东西:

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

    或者您可以先将它们组合成一个包。对应的 getExtra() 例程存在于另一端。有关详细信息,请参阅开发指南中的 the intent topic

    【讨论】:

    【解决方案3】:

    putExtra() : 该方法将数据发送到另一个活动,并且在参数中,我们必须传递键值对。

    语法:intent.putExtra("key", value);

    例如:intent.putExtra("full_name", "Vishnu Sivan");

    Intent intent=getIntent() :它从上一个活动中获取 Intent。

    fullname = intent.getStringExtra(“full_name”) :这一行从上一个活动中获取字符串,在参数中,我们必须传递我们在上一个活动中提到的密钥。

    示例代码:

    Intent intent = new Intent(getApplicationContext(), MainActivity.class);
    intent.putExtra("firstName", "Vishnu");
    intent.putExtra("lastName", "Sivan");
    startActivity(intent);
    

    【讨论】:

      猜你喜欢
      • 2014-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多