复选框的位置得到改变

时间:2014-04-04 05:44:37

标签: android checkbox filter

我正在尝试在我的自定义适配器上应用过滤器,扩展BaseAdapter,我面临一些问题,在根据EditText中的文本过滤输入并检查CheckBox以选择一个值,如果我删除了文本EditText用于搜索已选中复选框的位置发生变化的其他内容。

MainActivty

public class MainActivity extends Activity implements OnItemClickListener {

    EditText searchText;

    ArrayList<String> phno0 = new ArrayList<String>();
    List<String> arrayListNames;
    // private ListView listview;
    // private EditText edittext;
    public List<ProfileBean> list;
    public SearchableAdapter adapter;
    ProfileBean bean;

    String[] cellArray = null;
    String contacts;
    ListView lv;
    String phoneNumber, name;

    // StringBuilder b = new StringBuilder();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ActionBar actionBar = getActionBar();

        actionBar.setDisplayHomeAsUpEnabled(true);
        ColorDrawable colorDrawable = new ColorDrawable(
                Color.parseColor("#00aef0"));

        actionBar.setBackgroundDrawable(colorDrawable);
        setContentView(R.layout.get);
        // mStatusView = (TextView) findViewById(R.id.text1);
        searchText = (AutoCompleteTextView) findViewById(R.id.autocomplete);
        lv = (ListView) findViewById(R.id.listview);
        list = new ArrayList<ProfileBean>();

        getAllCallLogs(this.getContentResolver());

        adapter = new SearchableAdapter(getApplicationContext(), list);
        lv.setAdapter(adapter);
        lv.setItemsCanFocus(false);
        lv.setOnItemClickListener(this);
        lv.setTextFilterEnabled(true);

        contacts = SmsSend.contacts;

        if (SmsSend.contacts != null) {
            cellArray = contacts.split(";");
            //contacts=null;
            // Toast.makeText(getApplication(), contacts.toString(),
            // Toast.LENGTH_LONG).show();
            for (int i = 0; i < cellArray.length; i++) {

                for (int j = 0; j < list.size(); j++) {

                    if (cellArray[i].equals(list.get(j).getNumber())) {
                        adapter.setChecked(j, true);

                        // break;
                    }
                }

            }
        }



    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // TODO Auto-generated method stub
        getMenuInflater().inflate(R.menu.contact_main, menu);
        MenuItem searchItem = menu.findItem(R.id.action_search);

        return true;

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // TODO Auto-generated method stub

        switch (item.getItemId()) {

        case android.R.id.home:
            //StringBuilder checkedcontacts = new StringBuilder();
            // System.out.println(".............." +
            // adapter.mCheckStates.size());
            for (int i = 0; i < list.size(); i++)

            {
                if (adapter.mCheckStates.get(i) == true) {
                    phno0.add(list.get(i).getNumber());
                    //checkedcontacts.append(list.get(i).toString());
                //  checkedcontacts.append("\n");
                    // Toast.makeText(getApplicationContext(),
                    // list.get(i).getNumber().toString(),
                    // Toast.LENGTH_LONG).show();
                } else {
                    System.out.println("..Not Checked......"
                            + list.get(i).getNumber().toString());
                }

            }

            Intent returnIntent = new Intent();
            returnIntent.putStringArrayListExtra("name", phno0);
            setResult(RESULT_OK, returnIntent);

            finish();
            break;

        case R.id.addPage:

            break;
        case R.id.action_search:

            searchText.setVisibility(View.VISIBLE);
            searchText.addTextChangedListener(new TextWatcher() {
                @Override
                public void afterTextChanged(Editable arg0) {

                }

                @Override
                public void beforeTextChanged(CharSequence s, int start, int count,
                        int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before,
                        int count) {
                    adapter.getFilter().filter(s.toString());
                }
            });
            break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        // TODO Auto-generated method stub
phno0.clear();
        //StringBuilder checkedcontacts = new StringBuilder();
        // System.out.println(".............." + adapter.mCheckStates.size());
        for (int i = 0; i < list.size(); i++)

        {
            if (adapter.mCheckStates.get(i) == true) {
                phno0.add(list.get(i).getNumber());

            } else {
                System.out.println("..Not Checked......"
                        + list.get(i).getNumber().toString());
            }

        }

        Intent returnIntent = new Intent();
        returnIntent.putStringArrayListExtra("name", phno0);
        setResult(RESULT_OK, returnIntent);

        finish();

    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view,
            int position, long id) {
        // TODO Auto-generated method stub

            adapter.toggle(position);


    }

    public void getAllCallLogs(ContentResolver cr) {

        Cursor phones = cr.query(
                ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
                null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
                        + " ASC");
        while (phones.moveToNext()) {
            phoneNumber = phones
                    .getString(phones
                            .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            name = phones
                    .getString(phones
                            .getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));

            list.add(new ProfileBean(name, phoneNumber));

        }
        phones.close();
    }
}

SearchableAdapter

public class SearchableAdapter extends BaseAdapter implements Filterable, OnCheckedChangeListener {

    public SparseBooleanArray mCheckStates;
    private List<ProfileBean>originalData = null;
    private List<ProfileBean>filteredData = null;
    private LayoutInflater mInflater;
    private ItemFilter mFilter = new ItemFilter();

    public SearchableAdapter(Context context, List<ProfileBean> data) {
        //mCheckStates = new SparseBooleanArray(filteredData.size());
        mCheckStates = new SparseBooleanArray(data.size());
        this.filteredData = data ;
        this.originalData = data ;
        mInflater = LayoutInflater.from(context);
    }

    public int getCount() {
        return filteredData.size();
    }

    public Object getItem(int position) {
        return filteredData.get(position);
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {

         ViewHolder holder;
            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.row, null);


                holder = new ViewHolder();
                holder.name = (TextView) convertView.findViewById(R.id.textView1);
                holder.number = (TextView) convertView.findViewById(R.id.textView2);
                holder.chk = (CheckBox) convertView.findViewById(R.id.checkBox1);
                holder.chk.setTag(position);
                convertView.setTag(R.layout.row,holder);
            } else {
                holder = (ViewHolder) convertView.getTag(R.layout.row);
            }
            holder.chk.setOnCheckedChangeListener(null);

            holder.chk.setOnCheckedChangeListener(this);

            ProfileBean bean = filteredData.get(position);
            holder.name.setText(bean.getName());
            holder.number.setText(bean.getNumber());
            convertView.setTag(bean);
            return convertView;
        }

    static class ViewHolder {
        TextView name;
        TextView number;
        CheckBox chk;
    }

    public boolean isChecked(int position) {

        return mCheckStates.get(position, false);
    }

    public void setChecked(int position, boolean isChecked) {
        mCheckStates.put(position, isChecked);
    }

    public void toggle(int position) {
        setChecked(position, !isChecked(position));
    }



    public Filter getFilter() {
        return mFilter;
    }

    private class ItemFilter extends Filter {
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {

            String filterString = constraint.toString().toLowerCase();

            FilterResults results = new FilterResults();

            final List<ProfileBean> list = originalData;

            int count = list.size();
            final ArrayList<ProfileBean> nlist = new ArrayList<ProfileBean>(count);

            String filterableString ;

            for (int i = 0; i < count; i++) {

                ProfileBean bean =  list.get(i);
                filterableString = bean.getName();
                if (filterableString.toLowerCase().contains(filterString.toString().toLowerCase())) {
                    nlist.add(bean);
                }
            }

            results.values = nlist;
            results.count = nlist.size();

            return results;
        }

        @SuppressWarnings("unchecked")
        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            filteredData = (ArrayList<ProfileBean>) results.values;
            notifyDataSetChanged();
        }

    }





    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        // TODO Auto-generated method stub
        mCheckStates.put((Integer) buttonView.getTag(), isChecked);
    }




}

ProfileBean类

public class ProfileBean {
    private String name;
    private String number;
    //private boolean checked = false ;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getNumber() {
        return number;
    }
    public void setNumber(String number) {
        this.number = number;
    }


    public ProfileBean(String name, String number) {
        super();
        this.name = name;
        this.number = number;

    }



        }

1 个答案:

答案 0 :(得分:1)

像这样改变你的适配器..

public class SearchableAdapter extends BaseAdapter implements Filterable,
    OnCheckedChangeListener {

public SparseBooleanArray mCheckStates;
private List<ProfileBean> originalData = null;
private List<ProfileBean> filteredData = null;
private LayoutInflater mInflater;
private ItemFilter mFilter = new ItemFilter();

public SearchableAdapter(Context context, List<ProfileBean> data) {
    // mCheckStates = new SparseBooleanArray(filteredData.size());
    mCheckStates = new SparseBooleanArray(data.size());
    this.filteredData = data;
    this.originalData = data;
    mInflater = LayoutInflater.from(context);
}

public int getCount() {
    return filteredData.size();
}

public Object getItem(int position) {
    return filteredData.get(position);
}

public long getItemId(int position) {
    return position;
}

public View getView(int position, View convertView, ViewGroup parent) {

    ViewHolder holder;
    if (convertView == null) {
        convertView = mInflater.inflate(R.layout.row, null);

        holder = new ViewHolder();
        holder.name = (TextView) convertView.findViewById(R.id.textView1);
        holder.number = (TextView) convertView.findViewById(R.id.textView2);
        holder.chk = (CheckBox) convertView.findViewById(R.id.checkBox1);
        holder.chk.setTag(position);
        convertView.setTag(R.layout.row, holder);
    } else {
        holder = (ViewHolder) convertView.getTag(R.layout.row);
    }

    ProfileBean bean = filteredData.get(position);
    holder.name.setText(bean.getName());
    holder.number.setText(bean.getNumber());
    holder.chk.setOnCheckedChangeListener(null);
    holder.chk.setChecked(bean.isChecked);
    holder.chk.setOnCheckedChangeListener(this);
    convertView.setTag(bean);
    return convertView;
}

static class ViewHolder {
    TextView name;
    TextView number;
    CheckBox chk;
}

public void toggle(int position) {
    ProfileBean bean = filteredData.get(position);
    bean.isChecked = !bean.isChecked;
}

public android.widget.Filter getFilter() {
    return mFilter;
}

private class ItemFilter extends android.widget.Filter {

    @Override
    protected FilterResults performFiltering(CharSequence constraint) {

        String filterString = constraint.toString().toLowerCase();

        FilterResults results = new FilterResults();

        final List<ProfileBean> list = originalData;

        int count = list.size();
        final ArrayList<ProfileBean> nlist = new ArrayList<ProfileBean>(
                count);

        String filterableString;

        for (int i = 0; i < count; i++) {

            ProfileBean bean = list.get(i);
            filterableString = bean.getName();
            if (filterableString.toLowerCase().contains(
                    filterString.toString().toLowerCase())) {
                nlist.add(bean);
            }
        }

        results.values = nlist;
        results.count = nlist.size();

        return results;
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void publishResults(CharSequence constraint,
            FilterResults results) {
        filteredData = (ArrayList<ProfileBean>) results.values;
        notifyDataSetChanged();
    }
}

@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    // TODO Auto-generated method stub
    int position = (Integer) buttonView.getTag();
    ProfileBean profileBean = filteredData.get(position);
    profileBean.isChecked = isChecked;
    // mCheckStates.put((Integer) buttonView.getTag(), isChecked);

}
}

和你的bean类一样..

public class ProfileBean {
private String name;
private String number;
public boolean isChecked;

// private boolean checked = false ;
public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getNumber() {
    return number;
}

public void setNumber(String number) {
    this.number = number;
}

public ProfileBean(String name, String number) {
    super();
    this.name = name;
    this.number = number;

}

}

并保持相同......如此,让我们知道是否有任何问题..

像这样改变你的onBkpress方法..

@Override
public void onBackPressed() {
    phno0.clear();
    for (ProfileBean bean : list) {
        if (bean.isChecked) {
            phno0.add(bean.getNumber());
        } else {
            System.out.println("..Not Checked......"
                    + list.get(i).getNumber().toString());
        }
    }

    Intent returnIntent = new Intent();
    returnIntent.putStringArrayListExtra("name", phno0);
    setResult(RESULT_OK, returnIntent);

    finish();
}