Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
169 views
in Technique[技术] by (71.8m points)

android - implement search on a custom listview

i have a listview and EditText field and i wanna implement search, but my listview is a custom listview populated with array of objects of class Item. And when i press key whole listview gone so i guess the problem is that it cannot match char with object of class Item that's why there is no results when i press a key. this is my code

 filterText = (EditText) findViewById(R.id.editTextfilter);
 filterText.addTextChangedListener(filterTextWatcher);

    m_items = new ArrayList<Item>();
    phoneList=(ListView)findViewById(android.R.id.list);
    phoneList.setTextFilterEnabled(true);
     this.m_adapter = new ItemAdapter(this,R.layout.row,m_items);


     phoneList.setAdapter(this.m_adapter);

    private TextWatcher filterTextWatcher = new TextWatcher() {

    public void afterTextChanged(Editable s) {
    }

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

    public void onTextChanged(CharSequence s, int start, int before,
            int count) {

        m_adapter.getFilter().filter(s.toString());

    }

};

@Override
protected void onDestroy() {
    super.onDestroy();
    filterText.removeTextChangedListener(filterTextWatcher);
}

any help how to get it works

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I had a similar requirement. I have used a custom Filter.

    ArrayList<PostData> mPostingData = null;//arraylist of class items
    ArrayList<PostData> mTemp = new ArrayList<PostData>();//temporary arraylist of class items
    ArrayList<PostData> mOri = new ArrayList<PostData>();//Original arraylist
    getListView().setTextFilterEnabled(true);

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

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

         }

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


           }

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

POJO Class

     class PostData {
String mID; 
String mPostedBy;
String mTitle;
String mMessage;
String mImageUrl;
String mVideoUrl;
String mType ;
boolean me=false;
    }

Custom List View with Filter method overriden. Search based on mTitle of POJO Class

  class CustomListView extends ArrayAdapter {

Context context;
LayoutInflater mInflater;

private Bitmap mIcon1;
private Bitmap mIcon2;
private Bitmap mIcon3;
PostData mp ;

public  CustomListView(Context c)
{
     super(c, 0);
    mInflater = (LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    mIcon1 = BitmapFactory.decodeResource(c.getResources(), R.drawable.text_icon);
    mIcon2 = BitmapFactory.decodeResource(c.getResources(), R.drawable.image_icon);
    mIcon3 = BitmapFactory.decodeResource(c.getResources(), R.drawable.video_icon);
}   

public int getCount() {

    if(mPostingData!=null){
        return mPostingData.size();
    }else{
        return 0;
    }
}

 public void setData(ArrayList<PostData> mPpst) {   
    mPostingData = mPpst;//contains class items data.
}

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

             notifyDataSetInvalidated();
         }



        @Override
         protected FilterResults performFiltering(CharSequence constraint) {
             FilterResults result = new FilterResults();
             if (!TextUtils.isEmpty(constraint)) {
                 constraint = constraint.toString().toLowerCase();
                 ArrayList<PostData> foundItems = new ArrayList<PostData>();
                 if(mTemp!=null)
                 {
                 for(int i=0;i<mTemp.size();i++)
                 {
                    //If mTitle contains the string entered in Editext 
                     if (mTemp.get(i).mTitle.toString().contains(constraint)) {
                         foundItems.add(mTemp.get(i));

                     }
                     else
                     {

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


             return result;
         }
     };
 }
public Object getItem(int arg0) {
    // TODO Auto-generated method stub
    return arg0;
}

public View getView(int position, View convertView, ViewGroup parent) {
     ViewHolder holder;
    ///int type = getItemViewType(arg0);
     Log.i("Aru","get View");
    if(mPostingData == null ){

        return null;
    }
            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.listviewimg, null);
                convertView.setLayoutParams(new AbsListView.LayoutParams(LayoutParams.FILL_PARENT,
                        LayoutParams.WRAP_CONTENT));
                // Creates a ViewHolder and store references to the two children views
                // we want to bind data to.
                holder = new ViewHolder();
                holder.ll=(LinearLayout) convertView.findViewById(R.id.lvid);
                holder.text = (TextView) convertView.findViewById(R.id.texttitle);
                holder.text2 = (TextView) convertView.findViewById(R.id.tvst);
                holder.icon = (ImageView) convertView.findViewById(R.id.llimage);

                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            mp = mPostingData.get(position);

            String title = mp.mType;
            if(mp.mTitle!=null && Name.equals(mp.mPostedBy )){
                title = mp.mTitle+" "+title;
                //holder.text.setBackgroundColor(Color.WHITE);
                holder.ll.setBackgroundResource(R.drawable.listbkgme);
                holder.text.setText(title);
            }
            else if(mp.mTitle!=null && Name!=mp.mPostedBy)
            {
                title = mp.mTitle+" "+title;
           holder.text.setText(title);
            }


            if(mp.mMessage!=null && Name.equals(mp.mPostedBy )){
                holder.ll.setBackgroundResource(R.drawable.listbkgme);
                holder.text2.setText(mp.mMessage);

            }
            else if(mp.mMessage!=null && Name!=(mp.mPostedBy))
            {
                holder.text2.setText(mp.mMessage);
            }


            if(mp.mImageUrl!=null ){

                holder.icon.setImageBitmap(mIcon2);
            }else if(mp.mVideoUrl!=null){
                holder.icon.setImageBitmap(mIcon3);
            }else{
                holder.icon.setImageBitmap(mIcon1);
            }
       return convertView;
}
 class ViewHolder {
    TextView text;
    TextView text2;
    ImageView icon;
    LinearLayout ll;
}
public long getItemId(int position) {

    return position;
}
 }

Modify the above according to your requirements. I have tested the code and it works.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...