我在 ListView 中的 getView 方面遇到了一些严重的问题。问题是,我每行都有复选框。我需要与它们一起工作 - ListView 是 TabHost 的一部分,我需要记住选中了哪个 CheckBox 并在其他选项卡中使用它。
但是,我还有一个“主复选框”,用于检查 ListView 中的所有复选框。没什么大不了的,但问题是,我就是找不到在 ArrayList 中单击更改复选框状态的位置,我在其中保留了复选框的所有状态。每次我为每个 View 分配监听器时,“intposition”作为参数都会给出一些奇怪的数字,绝对不是我需要的数字 - 适配器中的位置,我打赌它类似于“现在屏幕上的位置......”
这是代码:
public View getView(int position, View convertView, ViewGroup parent) {
count = position;
View rowView = convertView;
SingleCarView sView = null;
if (rowView == null) {
LayoutInflater inflater = activity.getLayoutInflater();
rowView = inflater.inflate(R.layout.activity_overview_listview_row, null);
sView = new SingleCarView();
sView.cbx = (CheckBox)rowView.findViewById(R.id.overview_listview_chckbox);
sView.carName = (TextView)rowView.findViewById(R.id.overview_listview_label);
sView.state = (ImageView)rowView.findViewById(R.id.overview_listview_icon);
rowView.setTag(sView);
} else {
sView = (SingleCarView) rowView.getTag();
}
// THE TROUBLE BEGINS HERE...
sView.cbx.setChecked(savedState.get(position));
sView.cbx.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(computerActionWithCheckBox) {
// nothing
} else {
if(allCars.isChecked()) {
savedState.set(count, isChecked);
userModifiedCheckBox = true;
allCars.setChecked(false);
adapter.notifyDataSetChanged();
} else {
savedState.set(count, isChecked);
}
}
}
});
sView.carName.setText(objects.get(position));
switch(DataLoaderBeta.par.carState.get(position)){
case 1:
sView.state.setImageResource(R.drawable.ic_moving);
break;
case 2:
sView.state.setImageResource(R.drawable.ic_out_of_signal);
break;
case 0:
sView.state.setImageResource(R.drawable.ic_parked);
break;
}
return rowView;
}
非常感谢您的回答! :-)
最佳答案
在 getView()
方法中,设置为 CheckBox
的标签,并用整数表示从 getView()
方法获取的位置:
sView.cbx.setTag(new Integer(position));
然后在您的 OnCheckedChangeListener
中,您将获得被单击的复选框、buttonView
参数,并从此按钮获取标签 getTag()
并将该数字用作 savedState
中的位置:
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Integer realPosition = (Integer) buttonView.getTag(); //realPosition will be the real position you get in the getView() method
//other stuff here
关于android - 在 ListView 适配器中查找位置时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9584009/