在Android中过滤自定义ArrayAdapter

时间:2013-07-04 05:42:52

标签: android android-layout android-listview

我是Android的新手,我遵循了一些关于在ListView上添加搜索功能的教程,但在我的情况下,它不起作用。谁能告诉我我的代码有什么问题。

这是我的代码:

Activity.java

public class SendMoney extends Activity {
    private ListView lvContacts;
    private EditText etSearch;
    private ContactListAdapter mAdapter;
    private String[] stockArr, stockArr1, stockArr2;
    private Intent i;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_send_money);

        initObjects();

        ArrayList<String> phoneContactList = new ArrayList<String>();
        ArrayList<String> ContactImage = new ArrayList<String>();
        ArrayList<String> PhoneNumber = new ArrayList<String>();

        ContentResolver cr = getContentResolver();
        Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);

        if (cur.getCount() > 0) {
          while (cur.moveToNext()) {
            String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
            String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
            String img = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.PHOTO_THUMBNAIL_URI));

            if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
              // This inner cursor is for contacts that have multiple numbers.
              Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { id }, null);
              while (pCur.moveToNext()) {
                String pnumber = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

                ContactImage.add(img);
                phoneContactList.add(name);
                PhoneNumber.add(pnumber);

                Log.i("Contact List", pnumber);
              }
              pCur.close();
            }
          }

          Collections.sort(phoneContactList);
          int cnt = phoneContactList.size(); // Count of contacts

          // Convert ArrayList<String> to String[] START

          // Contacts Name
          stockArr = new String[phoneContactList.size()];
          stockArr = phoneContactList.toArray(stockArr);

          // Contacts Photo
          stockArr1 = new String[ContactImage.size()];
          stockArr1 = ContactImage.toArray(stockArr1);

          // Contacts Number
          stockArr2 = new String[PhoneNumber.size()];
          stockArr2 = PhoneNumber.toArray(stockArr2);

          // Convert ArrayList<String> to String[] END

          mAdapter = new ContactListAdapter(getApplicationContext(), R.layout.banks_listview_layout, stockArr, stockArr1);
          lvContacts.setAdapter(mAdapter);

        }
        cur.close();

        lvContacts.setTextFilterEnabled(true);
        lvContacts.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {             
                i = new Intent(SendMoney.this, SendMoneyForm.class);
                i.putExtra("contact_name", stockArr[position]);
                i.putExtra("contact_image", stockArr1[position]);
                i.putExtra("contact_number", stockArr2[position]);
                startActivity(i);
            }
        });


        //***************** SEARCH START ***********************

        etSearch.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
                // When user changed the Text
                mAdapter.getFilter().filter(cs.toString());
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                    int arg3) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable arg0) {
                // TODO Auto-generated method stub                          
            }
        });

        //***************** SEARCH END ***********************
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.send_money, menu);
        return true;
    }

    private void initObjects(){
        lvContacts = (ListView)findViewById(R.id.lvContacts);
        etSearch   = (EditText)findViewById(R.id.etSearch);
    }

我的自定义阵列适配器

public class ContactListAdapter extends ArrayAdapter<String> {
    private LayoutInflater mInflater;
    private String[] mStrings;
    private String[] mIcons;
    private int mViewResourceId;

    public ContactListAdapter(Context ctx, int resource,
            String[] option, String[] icons) {
        super(ctx, resource, option);

        mInflater = (LayoutInflater)ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mStrings = option;
        mIcons   = icons;    
        mViewResourceId = resource;

    }

     @Override
        public int getCount() {
            return mStrings.length;
        }

        @Override
        public String getItem(int position) {
            return mStrings[position];
        }

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

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            convertView = mInflater.inflate(mViewResourceId, null);

            ImageView iv = (ImageView)convertView.findViewById(R.id.ivBankIcon);
            if(mIcons[position]==null) {
                iv.setImageResource(R.drawable.default_picture);
            } else {
                iv.setImageURI(Uri.parse(mIcons[position]));
                Log.d("LALA", mIcons[position]);
            }

            TextView tv = (TextView)convertView.findViewById(R.id.tvBankName);
            tv.setText(mStrings[position]);

            return convertView;
        }
}

提前致谢!

2 个答案:

答案 0 :(得分:0)

在自定义适配器中添加此方法。你错过了这个方法

    @Override
    public Filter getFilter() {
        return new Filter() {
            @SuppressWarnings("unchecked")
            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {
                Log.d(Constants.TAG, "**** PUBLISHING RESULTS for: " + constraint);
                myData = (List<MyDataType>) results.values;
                MyCustomAdapter.this.notifyDataSetChanged();
            }

            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                Log.d(Constants.TAG, "**** PERFORM FILTERING for: " + constraint);
                List<MyDataType> filteredResults = getFilteredResults(constraint);

                FilterResults results = new FilterResults();
                results.values = filteredResults;

                return results;
            }
        };
    }

答案 1 :(得分:0)

您必须覆盖getFilter方法`并创建用于过滤数据的逻辑。

public Filter getFilter()

返回可用于使用过滤模式约束数据的过滤器。

此方法通常由Adapter类实现。

 EditText search= (EditText) findViewById(R.id.search);
 search.addTextChangedListener(new TextWatcher() {

     public void onTextChanged(CharSequence s, int start, int before, int count) {
                     adapter.getFilter().filter(s);

     }

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

       }

       public void afterTextChanged(Editable s) {
       }
      });

在适配器中

  @Override
  public Filter getFilter() {
  return new Filter() {
     @Override
     protected void publishResults(CharSequence constraint, FilterResults results) {
         if (results != null && results.count >= 0) {
             //if results of search is not null set the searched results data
         } else {
            // set original values
         }

         notifyDataSetInvalidated();
     }

然后

    @Override
     protected FilterResults performFiltering(CharSequence constraint) {
         FilterResults result = new FilterResults();
         if(condition)
            {

             ArrayList<MyDataType> foundItems = new ArrayList<MyDataType>();   
             // add items to foundItems if condition matches

             result.count = foundItems.size();//search results found return count
             result.values = foundItems;// return values
         }
         else
         {
             result.count=-1;// no search results found
         }


         return result;
     }
 };

}

示例:

Search in ListView with EditText