在 onListItemClick 中单独显示 HASHMAP 值

show HASHMAP values separately in onListItemClick

我正在使用 HASHMAP 在列表的单个列表项中显示两个项目,如以下代码所示。

public class MainActivity extends ListActivity {
HashMap<String, String> item;


 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ArrayList<Map<String, String>> list = buildData();
    String[] from = { "name", "purpose" };

    int[] to = { android.R.id.text1, android.R.id.text2 };

    SimpleAdapter adapter = new SimpleAdapter(this, list,
            android.R.layout.simple_list_item_2, from, to);
    setListAdapter(adapter);
    // setOnItemClickListener(selectLesson);
}

@Override
protected void onListItemClick(ListView l, View v, int    position, long id) {
    // TODO Auto-generated method stub
    super.onListItemClick(l, v, position, id);
    // Map<String, String> nn = list.get(position);

    String item1 = (String)           getListAdapter().getItem(position).toString();
    // item.get(name);


    Toast.makeText(this, item1, Toast.LENGTH_LONG).show();
}

private ArrayList<Map<String, String>> buildData() {
    ArrayList<Map<String, String>> list = new ArrayList<Map<String,String>>();
    list.add(putData("Android", "Mobile"));
    list.add(putData("Windows7", "Windows7"));
    list.add(putData("iPhone", "iPhone"));
    return list;
}

private HashMap<String, String> putData(String name, String purpose) {
    item = new HashMap<String, String>();
    item.put("name", name);
    item.put("purpose", purpose);


    return item;
}

}

我想要的是,每当我单击一个列表项时,键值应该单独显示 toasts.Currently 我在一个 toast 中同时显示,但不知道如何将它们分开。

替换下面的代码

String item1 = (String)getListAdapter().getItem(position).toString();
    Toast.makeText(this, item1, Toast.LENGTH_LONG).show();

String item1 = getListAdapter().getItem(position).getString("name");
   String item2 = getListAdapter().getItem(position).getString("purpose");
    Toast.makeText(this, item1, Toast.LENGTH_LONG).show();
    Toast.makeText(this, item2, Toast.LENGTH_LONG).show();

备注

"name" --> 根据您的选择第一个键

"purpose" --> 根据您的选择第二个键

您可以使用拆分功能拆分 "item1"

String item1=(String)getListAdapter().getItem(position).toString();
String[] parts = item1.split(" ");
String part1 = parts[0]; // Android
String part2 = parts[1]; // Mobile
 Toast.makeText(this, part1, Toast.LENGTH_LONG).show();
 Toast.makeText(this, part2, Toast.LENGTH_LONG).show();

拆分函数用于根据给定的条件拆分字符串。我在这里使用 space (" ") 将 item1 拆分为两个字符串。

当您点击一行时,onListItemClick 被触发。您可以使用 getItemAtPosition:

检索您单击的元素
HashMap<String, String> item = (HashMap<String, String>) l.getItemAtPosition(position);

并使用 get 方法从项目中检索信息

 String string = item.get("the_key_you_want_to_retrieve");