【问题标题】:How Can I Use SearchView with Filter mode in a ListView in API lever 8如何在 API 杠杆 8 的 ListView 中使用带有过滤模式的 SearchView
【发布时间】:2014-10-26 21:07:56
【问题描述】:

我正在使用minSdkVersion 8 开发Android 并使用ListView 在我的应用程序中显示移动联系人,但现在我还需要为列表视图添加过滤器,但我在sdkVersion 8 中找不到任何可以使用SearchView你们能帮忙吗?这是我的代码-

ArrayList<String> names = new ArrayList<String>();
ArrayList<String> phones = new ArrayList<String>();
ArrayList<String[]> selectedPhones = new ArrayList<String[]>();
ArrayList<String> selectedPhoneNumbers = new ArrayList<String>();

MyAdapter adapter;
Button done;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.contacts);
    ArrayList<String[]> oldContacts = (ArrayList<String[]>) getIntent()
            .getSerializableExtra("contacts");
    for (int i = 0; i < oldContacts.size(); i++) {
        selectedPhoneNumbers.add(oldContacts.get(i)[1]);
    }
    getAllCallLogs(this.getContentResolver());
    ListView lv = (ListView) findViewById(R.id.lvContactsSelecetion);
    adapter = new MyAdapter();
    lv.setAdapter(adapter);
    lv.setOnItemClickListener(this);
    lv.setItemsCanFocus(false);
    lv.setTextFilterEnabled(true);
    done = (Button) findViewById(R.id.bSelectContacts);
    done.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            for (int i = 0; i < names.size(); i++) {
                if (adapter.mCheckStates.get(i) == true) {
                    String[] contact = new String[] {
                            names.get(i).toString(),
                            phones.get(i).toString() };
                    selectedPhones.add(contact);
                }
            }
            Intent returnIntent = new Intent();
            returnIntent.putExtra("contacts", selectedPhones);
            setResult(RESULT_OK, returnIntent);
            finish();
        }
    });
}

public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
    adapter.toggle(arg2);
}

public void getAllCallLogs(ContentResolver cr) {
    Cursor contacts = cr.query(
            ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
            null, "DISPLAY_NAME ASC");
    while (contacts.moveToNext()) {
        String name = contacts
                .getString(contacts
                        .getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
        String phoneNumber = contacts
                .getString(contacts
                        .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
        names.add(name);
        phones.add(phoneNumber);
    }

    contacts.close();
}

class MyAdapter extends BaseAdapter implements
        CompoundButton.OnCheckedChangeListener {

    private SparseBooleanArray mCheckStates;
    LayoutInflater mInflater;
    TextView tv1, tv;
    CheckBox cb;

    MyAdapter() {
        mCheckStates = new SparseBooleanArray(names.size());
        mInflater = (LayoutInflater) Contacts.this
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

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

    public Object getItem(int position) {
        return position;
    }

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

    public View getView(final int position, View convertView,
            ViewGroup parent) {
        View vi = convertView;
        if (convertView == null)
            vi = mInflater.inflate(R.layout.row_contact, null);
        tv = (TextView) vi.findViewById(R.id.tvContactName);
        tv1 = (TextView) vi.findViewById(R.id.tvContactNumber);
        cb = (CheckBox) vi.findViewById(R.id.cbContactSelected);
        tv.setText("Name :" + names.get(position));
        tv1.setText("Phone No :" + phones.get(position));
        cb.setTag(position);
        if (selectedPhoneNumbers.contains(phones.get(position)))
            cb.setChecked(mCheckStates.get(position, true));
        else
            cb.setChecked(mCheckStates.get(position, false));
        cb.setOnCheckedChangeListener(this);

        return vi;
    }

    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 void onCheckedChanged(CompoundButton buttonView,
            boolean isChecked) {
        mCheckStates.put((Integer) buttonView.getTag(), isChecked);
    }
}

【问题讨论】:

    标签: android listview search filter


    【解决方案1】:

    简单的步骤:

    • 做一个简单的EditText
    • 对其应用过滤器

    示例代码:

    yourEditSearch.addTextChangedListener(new TextWatcher() {
                
                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    
                }
                
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count,
                        int after) {
                    
                }
                
                @Override
                public void afterTextChanged(Editable s) {
                    adapter.getFilter().filter(s);
                }
            };
    
    
    class MyAdapter extends BaseAdapter implements CompoundButton.OnCheckedChangeListener,  Filterable  {
           @Override
        public Filter getFilter() {
            Filter filter = new Filter() {
    
                @Override
                protected void publishResults(CharSequence constraint,
                        FilterResults results) {
    
                    // Now we have to inform the adapter about the new list filtered
                    if (results.count == 0)
                         notifyDataSetInvalidated();
                    else {
                        names= (ArrayList<String>) results.values;
                       notifyDataSetChanged();
                    }
                }
    
                @Override
                protected FilterResults performFiltering(CharSequence constraint) {
                    
    
                    // perform your search here using the searchConstraint String.
                      
                    constraint = constraint.toString().toLowerCase();
    
                   // check with the nane in list and add it
                   //iterate and check with the matching string
                   for (int i=0;i<names.size();i++) {
                        String dataNames = names.get(i);
                        if (dataNames.toLowerCase().contains(constraint.toString())) {
                             FilteredArrayNames.add(entity);
                      }
                    }
                    
                    results.count = FilteredArrayNames.size();
                    results.values = FilteredArrayNames;
    
                    return results;
                }
            };
            return filter;
        }
    
    }
    

    【讨论】:

      【解决方案2】:

      有一个类就是为此提供的支持库:

      SearchViewCompat

      【讨论】:

      • 有没有在菜单之外使用它?
      • 是的,所有使用 SearchView 的示例都可以轻松转换为 SearchViewCompat /跨度>
      • 谢谢,希望这对您有所帮助;)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-10
      • 1970-01-01
      • 2012-12-11
      • 2021-08-11
      • 2020-10-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多