【问题标题】:Android Studio - Click item in listview, get a value from that positionAndroid Studio - 单击列表视图中的项目,从该位置获取值
【发布时间】:2019-05-21 01:08:28
【问题描述】:

我正在尝试能够单击列表视图中的项目并获取 stopIdRoutes (String) 值并将其传递给另一个意图。

值在放入列表之前先放入 HashMap。

我曾尝试使用listview.getItemAtPosition(position);,但这只会引发错误:java.util.HashMap cannot be cast to ie.*.student.*.dublinbuses.getStopId。

我该如何解决这个问题。我在这里尝试了一些解决方案,但它们对这种情况没有帮助。

我还创建了一个 getStopId 类。

此外,发送到下一个意图的 stopIdRoutes 是列表中的最后一个停止 ID。

我的代码是:

    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            Intent i = new Intent(getApplicationContext(), StopIdResultsActivity.class);

            getStopId getstopid_fromclass = (getStopId)lv.getItemAtPosition(position);
            Log.i("Item", "Selected: " + getstopid_fromclass.getStopid());

            //Create the bundle
            Bundle bundle = new Bundle();

            //Add your data to bundle
            bundle.putString("stopid", stopidRoutes);

            //Add the bundle to the intent
            i.putExtras(bundle);

            //Fire that second activity
            startActivity(i);
        }

    });

【问题讨论】:

  • 嗨,您的 getStopId 类是什么样的?并且类名通常以大写字母开头,例如“GetStopId”。 (:
  • 我知道,我没有大写,所以如果它不起作用我会删除它。
  • 班级:public class getStopId { private String stopid; public getStopId(String stopid) { this.stopid = stopid; } public String getStopid(){ return stopid; } }

标签: java android-studio listview hashmap


【解决方案1】:
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            Intent i = new Intent(getApplicationContext(), StopIdResultsActivity.class);

            GetStopId getstopid_fromclass = list[position];


            //Create the bundle
            Bundle bundle = new Bundle();

            //Add your data to bundle
            bundle.putString("stopid", getstopid_fromclass.getStopid());

            //Add the bundle to the intent
            i.putExtras(bundle);

            //Fire that second activity
            startActivity(i);
        }

    })

在其他活动中得到它:-

String stopID = getIntent().getExtras().getString("stopid");

尝试使用这个,如果仍然出现错误,请告诉我错误

【讨论】:

  • 如果仍然出现错误,请告诉我错误。如果问题得到解决,请接受并投票赞成答案
  • 列表不正确,我尝试输入(可能)正确的列表名称resultList,但无法解析符号。这可能是因为它是一个 HashMap?
  • 你能指定你在这个listview适配器中传递的列表类型
  • 即使你传递了一个 hashmap,你也可以在那个位置获取键值对并从那个键值对中获取值
  • ArrayList&lt;HashMap&lt;String, String&gt;&gt; resultList;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-12-30
  • 1970-01-01
  • 1970-01-01
  • 2012-06-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多