【问题标题】:How to get a value from listview with multidimensional array?如何从具有多维数组的列表视图中获取值?
【发布时间】:2019-05-14 15:34:33
【问题描述】:

所以我的列表视图有一个多维数组,它的构造如下:

    String[][] listControls = {
            {"Shutdown Host","10"},
            {"Close Connection","1"}};

假设第一个字符串是我想在列表视图中显示的文本,另一个是要通过套接字发送的 id/消息(假设它是一个秘密值)。

我这样编写适配器:

    ArrayAdapter adapter = new ArrayAdapter<String>(this,R.layout.layout_listview);
        for(int i = 0; i < listControls.length; i++) {
            adapter.add(listControls[i][0]);
        }

    listView = (ListView) findViewById(R.id.controls_listView);
    listView.setAdapter(adapter);
    listView.setClickable(true);

我构建了一个项目的点击监听器:

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Object obj = listView.getItemAtPosition(position);

                //What should I add here? to get specific value from the array?
                //Integer cmdId = Integer.parseInt( ... );


            }
        });

从点击侦听器中,我想获取其他值,例如如果我在列表视图中单击“关闭连接”,我想从中获取“1”值并将其放入变量中。 提前感谢您的帮助。

【问题讨论】:

    标签: java android user-interface android-listview


    【解决方案1】:

    为您的案例编写自定义适配器。使用 HashMap 总是更好的。

    HashMap<String, Integer> map = new LinkedHashMap<>();
    map.add("Shut Down Host", 0);
    map.add("Close connection", 1);
    

    最重要的是使用 RecyclerView。

    RecyclerView 教程https://developer.android.com/guide/topics/ui/layout/recyclerview

    【讨论】:

    • HashMap 是一个不错的选择,比多维数组更好,但对于这个选项来说,类和对象仍然会更好。
    • 我创建了自定义适配器并为其使用了 hashmap。但是,如何调用该方法并使用位置返回单击侦听器中的哈希图值?谢谢
    • 没关系,我自己是从stackoverflow.com/questions/22449548/… 找到的。感谢您的帮助;)
    【解决方案2】:

    你可以做的是

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                      String value = listControls[position][1] 
                }
    

    当然,这只有在您有权访问 listControls 时才有效。如果没有,我会选择创建一个对象 SomethingWithCode(String text, Int code)[或者只是在 kotlin 中配对] 并创建一个自定义适配器。

    希望这会有所帮助!

    另外,你可能不需要多维数组,如果你总是只传递两个值(引用带有字符串和 int 参数的对象)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-03
      • 1970-01-01
      • 2011-06-25
      • 1970-01-01
      • 1970-01-01
      • 2015-05-20
      相关资源
      最近更新 更多