【问题标题】:Intent message passing confusion意图消息传递混乱
【发布时间】:2011-04-07 18:14:29
【问题描述】:

我对android中的意图和消息传递有点困惑。基本上我目前的困境:

当用户点击一行时,会向用户显示一个显示动物列表的屏幕,例如一只老虎,有关此动物的信息将显示在下一个屏幕/活动中。

我主要负责应用程序的框架,所以当用户从动物列表中选择时,他们会被带到 Animal 活动/类中,但在这个阶段它只是一个通用模型。

如何告诉应用程序选择了 TIGER,并向用户显示老虎数据。到目前为止我的方法

用户点击列表中的项目并调用活动:

protected void onListItemClick(ListView l, View v, int position, long id){
    Intent animalIntent = new Intent(this, Animal.class);
    startActivity(animalIntent);
}

【问题讨论】:

    标签: java android android-intent message


    【解决方案1】:

    为了扩展@PhilLello,一旦你使用了 Intent.setExtra(),你可以在你的活动中检索值:

    string animal;
    Bundle extras = this.getIntent().getExtras();
    if (extras != null) {
        animal = extras.getString("animal");
    }
    

    【讨论】:

    • 谢谢!!我其实还有一个问题,我怎么知道用户点击了哪一行。我的意思是,我不知道他们点击了老虎,他们可能点击了鹦鹉。这是通过 onListItemClick(int position) 完成?这意味着我正在使用静态列表,就是这种情况,我只是想知道是否有更好的方法
    • 您实际上会使用最后一个参数:long id 来引用单击的行 id。
    【解决方案2】:

    您可以将数据添加到您的意图中,因此在调用 startActivity 之前您可以:

    animalIntent.putExtra("myApp.chosenAnimal","Tiger");
    

    您可以使用不同的数据类型来代替上面的 Tiger 字符串、表示动物 ID 的整数、Tiger 对象等。

    现在在您的示例中,“Animal”类必须是一个活动,即在处理意图后加载的活动。如果 Animal 只是 POJO,您可能需要一个新活动来展示您的特定动物。

    进入 Animal 活动后,您可以使用以下命令检查传递的 Intent 的内容:

    Intent incomingIntent = getIntent();
    String selectedAnimal = incomingIntent.getStringExtra("myApp.chosenAnimal");
    

    注意传入意图区域中的“myApp.chosenAnimal”与animalIntent中的匹配。

    【讨论】:

      【解决方案3】:

      您可以在触发 Intent 之前使用Intent.setExtra("animal", "TIGER")。

      希望对你有帮助,

      菲尔·莱洛

      【讨论】:

      • 这个帮助很大!非常感谢!
      【解决方案4】:

      我之前问过这个问题,发现以下内容对我有用。在要发送数据的活动中放入以下内容。

      Intent i = new Intent();
      i.putExtra(KEY,String);
      i.putExtra(KEY2,String);
      

      当您想要接收此信息时,请运行以下命令。

      Bundle extras = getIntent().getExtras();
      String temp = extras.getString(KEY);
      String temp2 = extras.getString(KEY2);
      

      希望对你有帮助

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-01-05
        • 2011-01-21
        • 2018-09-12
        • 1970-01-01
        • 1970-01-01
        • 2013-04-28
        • 2019-08-23
        • 2013-09-08
        相关资源
        最近更新 更多