我正在尝试实现一段我发现的代码来存储 a 的状态,CheckBox
但ListView
它没有工作。有谁知道为什么我的适配器中的代码不起作用?
package kevin.erica.box;
import java.util.ArrayList;
import kevin.erica.box.R;
import android.R.color;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
public class MobileArrayAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] values;
private ArrayList<Boolean> itemChecked = new ArrayList<Boolean>();
public MobileArrayAdapter(Context context, String[] values) {
super(context, R.layout.list_adapter, values);
this.context = context;
this.values = values;
for (int i = 0; i < this.getCount(); i++) {
itemChecked.add(i, false); // initializes all items value with false
}
}
@Override
public View getView(final int position, View covertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.list_adapter, parent, false);
CheckBox textView = (CheckBox) rowView.findViewById(R.id.checkBox1);
textView.setTextColor(0xFFFFFFFF);
textView.setText(values[position]);
//Store state attempt
final CheckBox cBox = (CheckBox) rowView.findViewById(R.id.checkBox1); // your
// CheckBox
cBox.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v.findViewById(R.id.checkBox1);
if (cb.isChecked()) {
itemChecked.set(position, true);
// do some operations here
} else if (!cb.isChecked()) {
itemChecked.set(position, false);
// do some operations here
}
}
});
cBox.setChecked(itemChecked.get(position)); // this will Check or Uncheck the
// CheckBox in ListView
// according to their original
// position and CheckBox never
// loss his State when you
// Scroll the List Items.
return rowView;
}
}