Android中ListView包含CheckBox時滑動丟失選中狀態的解決

現象:listview 中,如果有10項,其中手機屏幕顯示1-6項,其餘的7-10項在屏幕中不可見,得向下滾動後才能看到,這個時候,如果選中1、2項,再滾動到7-10項,之後再滾動回來1-6項,就發現1、2項並未被選中。

解決方法: 編寫自定義的Adapter

public class TestAdapter extends ArrayAdapter<String> {
    private int resource;
    private LayoutInflater inflater;
    private boolean[] checks; //用於保存checkBox的選擇狀態

    public TestAdapter(Context context, int resource, List<String> list) {
        super(context, resource, list);
        checks = new boolean[list.size()];
        this.resource = resource;
        inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        if(convertView == null){
            convertView = inflater.inflate(resource, null);
            holder = new ViewHolder();
            holder.title = (TextView) convertView.findViewById(R.id.title);
            holder.checkBox = (CheckBox) convertView.findViewById(R.id.checkBox);
            convertView.setTag(holder);
        }else {
            holder = (ViewHolder) convertView.getTag();
        }
        holder.title.setText(getItem(position));
        final int pos  = position; //pos必須聲明爲final
        holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
            @Override
            public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
                checks[pos] = isChecked;
            }});
        holder.checkBox.setChecked(checks[pos]);
        return convertView;
    }
    static class ViewHolder {
        TextView title;
        CheckBox checkBox;
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章