Android ListView中获取选中行数据的方法
一开始我用的方法是这样的:
public void onItemClick(AdapterView<?> parent, View v, int position, long id) { View curr = parent.getChildAt((int) id); TextView c = (TextView)curr.findViewById(R.id.tvPopUpItem); String playerChanged = c.getText().toString(); Toast.makeText(Settings.this,playerChanged, Toast.LENGTH_SHORT).show(); }
但是滚动后再选择发现获取的值不对,正确的做法应该是这样的
public void onItemClick(AdapterView<?> parent, View v, int position, long id) { TextView c = (TextView) v.findViewById(R.id.tvPopUpItem); String playerChanged = c.getText().toString(); Toast.makeText(Settings.this,playerChanged, Toast.LENGTH_SHORT).show(); }
个人理解:onItemClick返回的View就是我们选中行的视图,再根据id查找当前视图中的控件,准确无疑!!!