在android中如何在列表视图中使用搜索视图来建议某种名称?

时间:2014-07-23 04:09:52

标签: android listview search

在android中如何在listview中使用searchview?
Listview包含imageview和多个textview
当我以前在搜索中键入一些文本时,列表视图想要根据我的搜索显示 如何执行此 提前致谢

2 个答案:

答案 0 :(得分:0)

像这样创建一个自定义适配器

public class PlanetAdapter extends ArrayAdapter<Planet> implements Filterable {

    private List<Planet> planetList;
    private Context context;
    private Filter planetFilter;
    private List<Planet> origPlanetList;

    public PlanetAdapter(List<Planet> planetList, Context ctx) {
        super(ctx, R.layout.img_row_layout, planetList);
        this.planetList = planetList;
        this.context = ctx;
        this.origPlanetList = planetList;
    }

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

    public Planet getItem(int position) {
        return planetList.get(position);
    }

    public long getItemId(int position) {
        return planetList.get(position).hashCode();
    }

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

        PlanetHolder holder = new PlanetHolder();

        // First let's verify the convertView is not null
        if (convertView == null) {
            // This a new view we inflate the new layout
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = inflater.inflate(R.layout.img_row_layout, null);
            // Now we can fill the layout with the right values
            TextView tv = (TextView) v.findViewById(R.id.name);
            TextView distView = (TextView) v.findViewById(R.id.dist);


            holder.planetNameView = tv;
            holder.distView = distView;

            v.setTag(holder);
        }
        else 
            holder = (PlanetHolder) v.getTag();

        Planet p = planetList.get(position);
        holder.planetNameView.setText(p.getName());
        holder.distView.setText("" + p.getDistance());


        return v;
    }

    public void resetData() {
        planetList = origPlanetList;
    }


    /* *********************************
     * We use the holder pattern        
     * It makes the view faster and avoid finding the component
     * **********************************/

    private static class PlanetHolder {
        public TextView planetNameView;
        public TextView distView;
    }



    /*
     * We create our filter 
     */

    @Override
    public Filter getFilter() {
        if (planetFilter == null)
            planetFilter = new PlanetFilter();

        return planetFilter;
    }



    private class PlanetFilter extends Filter {



        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            FilterResults results = new FilterResults();
            // We implement here the filter logic
            if (constraint == null || constraint.length() == 0) {
                // No filter implemented we return all the list
                results.values = origPlanetList;
                results.count = origPlanetList.size();
            }
            else {
                // We perform filtering operation
                List<Planet> nPlanetList = new ArrayList<Planet>();

                for (Planet p : planetList) {
                    if (p.getName().toUpperCase().startsWith(constraint.toString().toUpperCase()))
                        nPlanetList.add(p);
                }

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

            }
            return results;
        }

        @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 {
                planetList = (List<Planet>) results.values;
                notifyDataSetChanged();
            }

        }

    }
}

为行星创建POJO(getter setter类) 然后在你的活动中

//要显示的数据

List<Planet> planetsList = new ArrayList<Planet>();
    PlanetAdapter aAdpt;
 ListView lv = (ListView) findViewById(R.id.listView);
 aAdpt = new PlanetAdapter(planetsList, this);
        lv.setAdapter(aAdpt);

您可以像这样使用过滤

// TextFilter
          lv.setTextFilterEnabled(true);
          EditText editTxt = (EditText) findViewById(R.id.editTxt);          

          editTxt.addTextChangedListener(new TextWatcher() {

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    System.out.println("Text ["+s+"] - Start ["+start+"] - Before ["+before+"] - Count ["+count+"]");
                    if (count < before) {
                        // We're deleting char so we need to reset the adapter data
                        aAdpt.resetData();
                    }

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

                }

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

                }

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

答案 1 :(得分:0)

iam解决了这个问题,也使用了基础适配器你可以试试这个

公共类SubjectsActivity扩展了Activity {

private ImageView imgNavBarSubjectBook;
private ArrayList<String> arrSubjectResponse;
private ArrayList<String> arrChapterName;
private ArrayList<String> arrFileUrl;
private ArrayList<String> arrFileSize;
private ListView listChapter;
private TextView subjectName;

private EditText edtSearch;
private int textlength = 0;

// Google Analytics starts from here
private EasyTracker easyTracker = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_subjects);

    easyTracker = EasyTracker.getInstance(SubjectsActivity.this);

    subjectName = (TextView) findViewById(R.id.txtSubjectName);
    imgNavBarSubjectBook = (ImageView) findViewById(R.id.img_nav_bar_Subject_book);

    arrSubjectResponse = new ArrayList<String>();
    arrChapterName = new ArrayList<String>();
    arrFileUrl = new ArrayList<String>();
    arrFileSize = new ArrayList<String>();

    imgNavBarSubjectBook.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            finish();

        }
    });

    Typeface tf = Typeface.createFromAsset(getAssets(), "Georgia.ttf");
    subjectName.setTypeface(tf, Typeface.BOLD);

    Bundle bundle = getIntent().getExtras();
    if (bundle != null) {
        arrSubjectResponse = bundle
                .getStringArrayList("arr_subject_response");

        for (int i = 1; i < arrSubjectResponse.size(); i = i + 8) {
            arrChapterName.add(arrSubjectResponse.get(i + 2));
            arrFileUrl.add(arrSubjectResponse.get(i + 6));
            arrFileSize.add(arrSubjectResponse.get(i + 5));

        }
    }
    listChapter = (ListView) findViewById(R.id.listChapter);

    subjectName.setText(CoursesAdapter.Subject_Name);

    listChapter.setAdapter(new SubjectAdapter(SubjectsActivity.this,
            arrChapterName, arrFileUrl, arrFileSize));

    edtSearch = (EditText) findViewById(R.id.edtSearchSubjects);

    edtSearch.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {
            // TODO Auto-generated method stub
            textlength = edtSearch.getText().length();
            arrChapterName.clear();
            arrFileUrl.clear();

            for (int i = 1; i < arrSubjectResponse.size(); i = i + 8) {

                String name = arrSubjectResponse.get(i + 2);
                String searchtext = String.valueOf(s);// edtSearch.getText().toString();
                if (textlength <= arrSubjectResponse.get(i + 2).length()) {

                    if (name.toLowerCase().indexOf

                    (searchtext.toLowerCase()) != -1) {
                        Log.d("",
                                "------------Entered add value to list-----");
                        arrChapterName.add(arrSubjectResponse.get(i + 2));
                        arrFileUrl.add(arrSubjectResponse.get(i + 6));
                        arrFileSize.add(arrSubjectResponse.get(i + 5));
                    }
                }
            }

            listChapter.setAdapter(new SubjectAdapter(
                    SubjectsActivity.this, arrChapterName, arrFileUrl,
                    arrFileSize));
            Log.d("", "Chapter------->" + arrChapterName);
            Log.d("", "Fileurl---------->" + arrFileUrl);
        }

        @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

        }
    });

}

@Override
public void onStart() {
    super.onStart();
    EasyTracker.getInstance(this).activityStart(this);
}

@Override
public void onStop() {
    super.onStop();
    EasyTracker.getInstance(this).activityStop(this);
}

}