ListView搜索工具Android

时间:2016-07-07 09:20:10

标签: android listview

我希望在ListView上实施搜索功能。到目前为止,我已成功填充ListView个工作,我有一个EditText字段用作我的搜索框。到目前为止,这是我的代码;

public class CurrentJobsActivity : Activity
    {
        private ListView listView;
        private EditText inputSearch;

        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.CurrentJobs);
            LoadCurrentJobs();
        }

        private void LoadCurrentJobs()
        {
            var _currentJobsService = new CurrentJobsService();
            var listOfJobs = _currentJobsService.GetJobList("currentjobs");

            listView = FindViewById<ListView>(Resource.Id.currentJobsListView);
            inputSearch = FindViewById<EditText>(Resource.Id.inputSearch);

            listView.Adapter = new JobListAdapter(this, listOfJobs);
            listView.ItemClick += OnListItemClick;

            inputSearch.TextChanged += InputSearchOnTextChanged;
        }

        private void InputSearchOnTextChanged(object sender, TextChangedEventArgs e)
        {
            listView.SetFilterText(inputSearch.Text);
        }

正如您所看到的,我尝试使用listView.SetFilterText(inputSearch.Text);进行搜索,但是当用户输入时没有任何反应。如何修改它以实现搜索功能?

3 个答案:

答案 0 :(得分:0)

您需要在列表视图中启用文本过滤器。

listView.setTextFilterEnabled(true);

更改为:

private void LoadCurrentJobs()
{
    var _currentJobsService = new CurrentJobsService();
    var listOfJobs = _currentJobsService.GetJobList("currentjobs");

    listView = FindViewById<ListView>(Resource.Id.currentJobsListView);
    inputSearch = FindViewById<EditText>(Resource.Id.inputSearch);

    listView.Adapter = new JobListAdapter(this, listOfJobs);
    listView.ItemClick += OnListItemClick;
    listView.setTextFilterEnabled(true);
    inputSearch.TextChanged += InputSearchOnTextChanged;
}

答案 1 :(得分:0)

你可以找到一个完整的样本Here(我觉得转换为C#非常容易):

package com.androidhive.androidlistviewwithsearch;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;

public class MainActivity extends Activity {

    // List view
    private ListView lv;

    // Listview Adapter
    ArrayAdapter<String> adapter;

    // Search EditText
    EditText inputSearch;


    // ArrayList for Listview
    ArrayList<HashMap<String, String>> productList;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Listview Data
        String products[] = {"Dell Inspiron", "HTC One X", "HTC Wildfire S", "HTC Sense", "HTC Sensation XE",
                                "iPhone 4S", "Samsung Galaxy Note 800",
                                "Samsung Galaxy S3", "MacBook Air", "Mac Mini", "MacBook Pro"};

        lv = (ListView) findViewById(R.id.list_view);
        inputSearch = (EditText) findViewById(R.id.inputSearch);

        // Adding items to listview
        adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.product_name, products);
        lv.setAdapter(adapter);

        /**
         * Enabling Search Filter
         * */
        inputSearch.addTextChangedListener(new TextWatcher() {

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

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

答案 2 :(得分:0)

如果您正在解析数据并将其显示在listview中,请尝试这种方式,这对我有用

public class FriendsFragment extends Fragment {



    private ProgressDialog pDialog;

    // Creating JSON Parser object
    JSONparserr jsonParser = new JSONparserr();

    ArrayList<HashMap<String, String>> WebsiteList;

    // albums JSONArray
    JSONArray data = null;
    String link_url;

    ArrayList<HashMap<String, String>> arrayTemplist;

    private AutoCompleteTextView inputSearch;

    private ListView lv;


    private static final String URL_ALBUMS = "your url";

    private static final String WEBSITE_MENU_ID = "subcategoryname";

    private static final String TAG_MATCH = "subcategorylist";
    private static final String TAG_PROFILE = "CatId";
    private static final String TAG_SUBCATID = "SubId";
    //private static final String TAG_CAST="Company";
    private int ab;
    private String adi;
    int current_page = 0;
    public String pgcount;
    private JSONArray addbanners;
    private String imggg;
    private String counts;
    private String totpage;
    private String curpage;
    private JSONArray interestaccept;

    private static final String BANERARR="add";


    private static final String BANNER_PIC="addimg";
    private ImageView banimgs;

    public FriendsFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.products_activity, container, false);
        getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);


        lv = (ListView) rootView.findViewById(R.id.listpehlu);

        banimgs=(ImageView)rootView.findViewById(R.id.addbannercat);
        WebsiteList = new ArrayList<HashMap<String, String>>();
        new LoadBrandBanner().execute();
        // Loading Albums JSON in Background Thread
        new LoadCatagory().execute();
        inputSearch = (AutoCompleteTextView) rootView.findViewById(R.id.autoCompleteTextViewhomefrag);

        inputSearch.addTextChangedListener(new TextWatcher() {


            @Override
            public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {

                arrayTemplist = new ArrayList<HashMap<String, String>>();
                String searchString = inputSearch.getText().toString().toLowerCase();

                for (int i = 0; i < WebsiteList.size(); i++) {
                    String currentString = WebsiteList.get(i).get(FriendsFragment.this.WEBSITE_MENU_ID);
                    if (currentString.toLowerCase().startsWith(searchString)) {
                        arrayTemplist.add(WebsiteList.get(i));
                    }
                }

                for (int i = 0; i < arrayTemplist.size(); i++) {
                    String currentstrin = arrayTemplist.get(i).get(FriendsFragment.this.WEBSITE_MENU_ID);
                    //Toast.makeText(getApplicationContext(), currentstrin, Toast.LENGTH_LONG).show();

                }
                SimpleAdapter adapters = new SimpleAdapter(getActivity(), arrayTemplist, R.layout.list_item_match, new String[]{WEBSITE_MENU_ID
                }, new int[]{
                        R.id.txtbrndnm});
                lv.setAdapter(adapters);

            }

            @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
            }
        });
        return rootView;
    }



    class LoadCatagory extends AsyncTask<String, String, ArrayList<HashMap<String, String>>> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(FriendsFragment.this.getActivity());
            pDialog.setMessage("Loading...");
            pDialog.setIndeterminate(true);
            // pDialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.custom_progress));
            pDialog.setCancelable(false);
            pDialog.show();
        }

        protected ArrayList<HashMap<String, String>> doInBackground(String... args) {
            ServiceHandler sh = new ServiceHandler();
            // Making a request to url and getting response
            ArrayList<HashMap<String, String>> data = new ArrayList<HashMap<String, String>>();
            String jsonStr = sh.makeServiceCall(URL_ALBUMS, ServiceHandler.GET);

            Log.d("Response: ", "> " + jsonStr);

            if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);

                    // Getting JSON Array node
                    interestaccept = jsonObj.getJSONArray(TAG_MATCH);

                    for (int i = 0; i < interestaccept.length(); i++) {
                        JSONObject c = interestaccept.getJSONObject(i);
                        HashMap<String, String> map = new HashMap<String, String>();
                        map.put(WEBSITE_MENU_ID, c.getString(WEBSITE_MENU_ID));
                        map.put(TAG_PROFILE, c.getString(TAG_PROFILE));
                        map.put(TAG_SUBCATID, c.getString(TAG_SUBCATID));
                        //map.put(TAG_COUNT, c.getString(TAG_COUNT));
                        WebsiteList.add(map);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                Log.e("ServiceHandler", "Couldn't get any data from the url");
            }
            return null;
        }

        protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
            super.onPostExecute(result);

            // dismiss the dialog after getting all albums
            if (pDialog.isShowing())
                pDialog.dismiss();
            // updating UI from Background Thread

            ListAdapter adapter = new SimpleAdapter(
                    getActivity(), WebsiteList,
                    R.layout.list_item_match, new String[]{WEBSITE_MENU_ID
            }, new int[]{
                    R.id.txtbrndnm});
            lv.setAdapter(adapter);


            lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {


                    Intent intent=new Intent(getActivity(),Productss.class);
                    intent.putExtra("catidss", WebsiteList.get(i).get(TAG_PROFILE));
                    intent.putExtra("subcatidss", WebsiteList.get(i).get(TAG_SUBCATID));
                    startActivity(intent);
                }
            });
        }

    }


}