我正在从listview中点击的元素中检索字符串数据。
该元素有两行,一行名为“current”,另一行名为“name”。 在我的listItemOnClick()中,我获取了被单击的项目,然后对其执行toString()。我得到的是这样的:
{current=SOMETHING, name=SOMETHING}
我的问题是如何将这些分开?这是我的onclick代码:
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();
}
答案 0 :(得分:4)
你可以这样做(当格式发生变化时,丑陋且容易出现未来错误) - 如果字符串格式不正确,请添加错误检查:
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");
答案 1 :(得分:3)
findViewById
找到各个文本视图并从中获取文本。使用你的代码就像这样:
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
TextView nameTxt = (TextView) v.findViewById(R.id.Text1);
TextView currentTxt = (TextView) v.findViewById(R.id.Text2);
String name = nameTxt.getText().toString();
String current = currentTxt.getText().toString();
}
希望这有帮助!
答案 2 :(得分:0)
这应该不是很困难:
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();
// first remove the first and last brace
current = current.substring(1,current.length()-1);
// then split on a comma
String[] elements = current.split(",");
// now for every element split on =
String[] subelements = elements[0].split("=");
String key1 = subelements[0];
String value1 = subelements[1];
subelements = elements[1].split("=");
String key2 = subelements[0];
String value2 = subelements[1];
((TextView) findViewById(R.id.check)).setText(current);
}