0

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

这是我的代码:

活动.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;
        }
}

提前致谢!

4

2 回答 2

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;
     }
 };

}

例子:

使用 EditText 在 ListView 中搜索

于 2013-07-04T05:52:22.553 回答
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;
            }
        };
    }
于 2013-07-04T05:48:54.803 回答