我将如何在自定义列表VIew中使用搜索

时间:2013-01-24 07:40:08

标签: android list search

我在定制搜索上花了太多时间 任何人都可以告诉我,我将如何在我的code.Plz帮助中实现它 我已经在列表中获取数据,我有编辑框,但我不知道,它将如何实现在使用Filterable类或我将如何使用  此代码中为addTextChangedListener(){}

  editTxt.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) {
     }
 });

我的代码是 MainSearch.java ,我将获得列表。

在此次通话中,我将实施搜索代码。 我有点想法,如果我将所有列表项保存在arrayList中,并将所有这些值与editText值进行比较。它可以提供解决方案。不确定。

public class MainSEarch extends Activity {

    // Progress Dialog
        private ProgressDialog pDialog;
    ListView list;
    LazyAdapter adapter;

    // Connection detector
        ConnectionDetector cd;

        // Alert dialog manager
        AlertDialogManager alert = new AlertDialogManager();



        ArrayList<HashMap<String, String>> contactList;
    // Search EditText
   EditText inputSearch;
   int textlength = 0;




    // url to make request
    String url = "URl NOT HERE But like  as  http://api.androidhive.info/contacts/"; 


    // JSON Node names
        static final String TAG_CONTACTS = "userinfo";
         static final String TAG_ID = "id";
          static final String TAG_NAME = "name";
          static final String TAG_EMAIL = "email";
          static final String TAG_PHONE = "cb_phonenumber";

    // contacts JSONArray
    JSONArray userinfo = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list_search);
        inputSearch = (EditText) findViewById(R.id.editText1); // Search Box

        cd = new ConnectionDetector(getApplicationContext());

       // Check for internet connection
       if (!cd.isConnectingToInternet()) {
           // Internet Connection is not present
           alert.showAlertDialog(MainSEarch.this, "Internet Connection Error",
                   "Please connect to working Internet connection", false);
           // stop executing code by return
           return;
       }



        // Hashmap for ListView
         contactList = new ArrayList<HashMap<String, String>>();


        // Loading Agents list JSON in Background Thread
                new LoadAgentList().execute();


                inputSearch.addTextChangedListener(new TextWatcher() {

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {
            //what should I do in this method.plz provide some solutions.           

                        }

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

                    }

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

    }



    /**
     * Background Async Task to Load all Albums by making http request
     * */
    class LoadAgentList extends AsyncTask<String, String, String> 
    {


    /** *
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(MainSEarch.this);
            pDialog.setMessage("Agents List ...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        @Override
        protected String doInBackground(String... params) {
            // TODO Auto-generated method stub



            // Creating JSON Parser instance
                    JSONParser jParser = new JSONParser();

                    // getting JSON string from URL
                    JSONObject json = jParser.getJSONFromUrl(url);

                    try{

                        // Getting Array of Contacts
                        userinfo = json.getJSONArray(TAG_CONTACTS);

                        // looping through All Contacts
                        for(int i = 0; i < userinfo.length(); i++){
                            JSONObject c = userinfo.getJSONObject(i);

                            // Storing each json item in variable
                            String id = c.getString(TAG_ID);
                            String name = c.getString(TAG_NAME);
                            String email = c.getString(TAG_EMAIL);
                            String mobile = c.getString(TAG_PHONE);




                            // creating new HashMap
                            HashMap<String, String> map = new HashMap<String, String>();

                            // adding each child node to HashMap key => value
                            map.put(TAG_ID, id);
                            map.put(TAG_NAME, name);
                            map.put(TAG_EMAIL, email);
                            map.put(TAG_PHONE, mobile);

                            // adding HashList to ArrayList
                            contactList.add(map);
                        }
                    }
                        catch (JSONException e) {
                            e.printStackTrace();
                        }

            return null;
        }



            @Override
            protected void onPostExecute(String file_url) {
                // dismiss the dialog after getting all albums
                pDialog.dismiss();
                // updating UI from Background Thread
                runOnUiThread(new Runnable() {
                    public void run() {


                        list=(ListView)findViewById(R.id.mylist);

                        // Getting adapter by passing xml data ArrayList
                        adapter=new LazyAdapter(MainSEarch.this,contactList);      
                        list.setAdapter(adapter);
                    }
                });

            }

    }

我的第二课 LazyAdapter :这将展示如何getView() 方法膨胀视图以及惰性列表将如何工作代码 我在这堂课中做了什么

public class LazyAdapter extends BaseAdapter {

    private Activity activity;
    private ArrayList<HashMap<String, String>> data;
    private static LayoutInflater inflater=null;

    public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
        activity = a;
        data=d;
        inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    }


    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return data.size();
    }

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

    @Override
    public long getItemId(int arg0) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
         View vi=convertView;
            if(convertView==null)
                vi = inflater.inflate(R.layout.list_item, null);

            TextView name = (TextView)vi.findViewById(R.id.name); // name
            TextView email = (TextView)vi.findViewById(R.id.email); //  email
            TextView phone = (TextView)vi.findViewById(R.id.mobile); // phone


            HashMap<String, String> song = new HashMap<String, String>();
            song = data.get(position);

            // Setting all values in listview
            name.setText(song.get(MainSEarch.TAG_NAME));
            email.setText(song.get(MainSEarch.TAG_EMAIL));
            phone.setText(song.get(MainSEarch.TAG_PHONE));




        return vi;
    }




}

我的代码应该有什么变化,我的搜索将会执行。  Plz我是Android的初学者。  在此先感谢

3 个答案:

答案 0 :(得分:1)

看看这个例子。希望你能得到一个主意。使用Textwatcher。 http://abdennour-insat.blogspot.in/2012/05/listview-textwatcher-autocomplete.html

答案 1 :(得分:0)

我使用以下代码从我的自定义列表视图中过滤数据。看看它,如果你可以在你的情况下实现它,dcheck,

adapter = new CustomListViewAdapter(this,R.layout.list_row, rowItems);
listView.setAdapter(adapter);
listView.setTextFilterEnabled(true);

并且根据编辑文本过滤搜索,我使用了

editText.addTextChangedListener(new TextWatcher() {

            public void onTextChanged(CharSequence arg0, int arg1, int arg2,
                    int arg3) {

            }

            public void beforeTextChanged(CharSequence arg0, int arg1,
                    int arg2, int arg3) {

            }

            public void afterTextChanged(Editable arg0) {
                ActivityName.this.adapter.getFilter().filter(arg0);

            }
        });

答案 2 :(得分:0)

你必须在自定义适配器中实现自己的过滤器,这里是一个样本(非常简单):

public Filter getFilter() {
        Log.d("Filter", "BeginFilter");
        return new Filter() {
                @SuppressWarnings("unchecked")
                @Override
                protected void publishResults(CharSequence arg0, FilterResults arg1) {
                    Log.d("Filter", "publishResults");
                    mGuides = (ArrayList<Guide>)arg1.values;
                    notifyDataSetChanged();
                }

                @Override
                protected FilterResults performFiltering(CharSequence constraint) {
                    Log.d("Filter","Perform filtering");

                    constraint = constraint.toString().toLowerCase();

                    ArrayList<Guide> filteredGuides = new ArrayList<Guide>();

                    for (int i = 0; i < mGuides.size(); i++)
                    {
                        Guide newGuide = mGuides.get(i);
                        if (newGuide.getName().toLowerCase().contains(constraint))
                            filteredGuides.add(newGuide);
                    }

                    FilterResults filterResults = new FilterResults();
                    filterResults.count = filteredGuides.size();
                    filterResults.values = filteredGuides;
                    return filterResults;
                }
            };
    }

你可以从活动中这样称呼它:

public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
                adapter.getFilter().filter(arg0);
            }
相关问题