我正在从我的 ListView 中单击的元素中检索字符串数据。
该元素有两行,一行名为“current”,另一行名为“name”。 在我的 listItemOnClick() 中,我正在获取被单击的项目,然后对其执行 toString()。我得到的是这样的:
{current=SOMETHING, name=SOMETHING}
我的问题是如何将它们分开?这是我的点击代码:
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
Object o = this.getListAdapter().getItem(position);
String current = o.toString();
((TextView) findViewById(R.id.check)).setText(current);
}
例如,我只想显示电流。谢谢!
编辑
我的列表变量:
static final ArrayList<HashMap<String,String>> listItems =
new ArrayList<HashMap<String,String>>();;
SimpleAdapter adapter;
创建列表:
for(int i=0; i<num_enter; i++){
final int gi = i;
adapter=new SimpleAdapter(this, listItems, R.layout.custom_row_view,new String[]{"name", "current"}, new int[] {R.id.text1, R.id.text2});
setListAdapter(adapter);
HashMap<String,String> temp = new HashMap<String,String>();
temp.put("name", name[i]);
temp.put("current", "Value: " + Integer.toString(current[i]));
listItems.add(temp);
adapter.notifyDataSetChanged();
}
最佳答案
你可以那样做(当格式改变时/如果格式改变时很丑陋并且将来容易出错) - 添加错误检查以防字符串格式不正确:
String s = "{current=CURRENT, name=NAME}";
s = s.substring(1, s.length() - 1); //removes { and }
String[] items = s.split(",");
String current = items[0].split("=")[1]; //CURRENT
String name = items[1].split("=")[1]; //NAME
在你的编辑之后,似乎 o 是一个 Map 所以你也可以写(更好):
Map<String, String> map = (Map<String, String>) this.getListAdapter().getItem(position);
String current = map.get("current");
String name = map.get("name");
关于Android - 分隔列表字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10519473/