简体   繁体   English

EditText用于过滤listview中的项目。 如何?

[英]EditText to filter items in listview. How to?

I've got a listview that shows the applications installed in my device. 我有一个列表视图,显示我的设备中安装的应用程序。 I want create a editText that filter the items i search. 我想创建一个editText来过滤我搜索的项目。 I've already create the edittext but doesn't work and nothing appear when i type to search something. 我已经创建了edittext但是没有工作,当我输入搜索内容时没有任何内容出现。 This is the MainActivity: 这是MainActivity:

public class MainActivity extends ListActivity implements OnItemLongClickListener{
    private PackageManager packageManager = null;
    private List<ApplicationInfo> applist = null;
    private ApplicationAdapter listadaptor = null;
    EditText inputSearch;

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

        packageManager = getPackageManager();
        new LoadApplications().execute();

        /** refresh btn*/
        Button bottone1 = (Button)findViewById(R.id.button1);
        bottone1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                new LoadApplications().execute();

            }   
        });
        /** EditText filter */
        // Edit text
        inputSearch = (EditText) findViewById(R.id.editTxt);
        ListView lv = (ListView) findViewById(android.R.id.list);
        lv.setTextFilterEnabled(true);

        inputSearch.addTextChangedListener(new TextWatcher() {

            public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
                // Filter when someone type in the edittext
                MainActivity.this.listadaptor.getFilter().filter(cs);   
            }

            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                    int arg3) {
                // TODO Auto-generated method stub

            }

            public void afterTextChanged(Editable arg0) {
                // TODO Auto-generated method stub                          
            }
        });
    };



    private List<ApplicationInfo> checkForLaunchIntent(List<ApplicationInfo> list) {
        ArrayList<ApplicationInfo> applist = new ArrayList<ApplicationInfo>();
        for (ApplicationInfo info : list) {
            try {
                if (null != packageManager.getLaunchIntentForPackage(info.packageName)) {
                    applist.add(info);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return applist;
    }


    private class LoadApplications extends AsyncTask<Void, Void, Void> {        

        public ProgressDialog progress = null;

        @Override
        protected Void doInBackground(Void... params) {
            applist = checkForLaunchIntent(packageManager.getInstalledApplications(PackageManager.GET_META_DATA));
            listadaptor = new ApplicationAdapter(MainActivity.this,R.layout.snippet_list_row, applist);

            return null;
        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
        }

        protected void onDestroy() {
            if(progress!=null)
                if(progress.isShowing()){
                progress.dismiss();
                }

        }

        @Override
        protected void onPostExecute(Void result) {
            setListAdapter(listadaptor);
            progress.dismiss();
            super.onPostExecute(result);
        }

        @Override
        protected void onPreExecute() {
            progress = ProgressDialog.show(MainActivity.this, null,
                    "Loading...");
            super.onPreExecute();
        }

        @Override
        protected void onProgressUpdate(Void... values) {
            super.onProgressUpdate(values);
        }
    }


    @Override
    public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2,
            long arg3) {
        // TODO Auto-generated method stub
        return false;
    }

}

And the Adapter EDITED: 和编辑的适配器:

    public class ApplicationAdapter extends ArrayAdapter<ApplicationInfo>  { 
    private List<ApplicationInfo> appsList = null; 
    private Context context; 
    private PackageManager packageManager; 

    public ApplicationAdapter(Context context, int textViewResourceId, 
            List<ApplicationInfo> appsList) { 
        super(context, textViewResourceId, appsList); 
        this.context = context; 
        this.appsList = appsList; 
        packageManager = context.getPackageManager(); 
    } 

    @Override
    public int getCount() { 
        return ((null != appsList) ? appsList.size() : 0); 
    } 

    @Override
    public ApplicationInfo getItem(int position) { 
        return ((null != appsList) ? appsList.get(position) : null); 
    } 

    @Override
    public long getItemId(int position) { 
        return position; 
    } 

    @Override
    public View getView(int position, View convertView, ViewGroup parent) { 
        View view = convertView; 
        if (null == view) { 
            LayoutInflater layoutInflater = (LayoutInflater) context 
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
            view = layoutInflater.inflate(R.layout.snippet_list_row, null); 
        } 



        ApplicationInfo data = appsList.get(position); 
        if (null != data) { 
            TextView appName = (TextView) view.findViewById(R.id.app_name); 
            TextView packageName = (TextView) view.findViewById(R.id.app_paackage); 
            ImageView iconview = (ImageView) view.findViewById(R.id.app_icon); 

            appName.setText(data.loadLabel(packageManager)); 
            packageName.setText(data.packageName); 
            iconview.setImageDrawable(data.loadIcon(packageManager)); 
        } 
        return view; 
    } 

    @Override
    public Filter getFilter() {

        Filter filter = new Filter() {

            @SuppressWarnings("unchecked")
            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {

                appsList = (List<ApplicationInfo>) results.values;
                notifyDataSetChanged();
            }

            @Override
            protected FilterResults performFiltering(CharSequence constraint) {

                FilterResults results = new FilterResults();
                ArrayList<String> FilteredArrayNames = new ArrayList<String>();

                // perform your search here using the searchConstraint String.



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



                return results;
            }
        };

        return filter;
    }
};

Someone can help me? 有人可以帮帮我吗? Actually when i type to search nothing change and rest the whole listview. 实际上,当我键入搜索没有任何改变并休息整个列表视图。 Thanks 谢谢

Take a look at the Filterable interface and implement it in your Adapter class. 查看Filterable接口并在Adapter类中实现它。 Define the getFilter() method of the interface which will return the filtered list items in the adapter. 定义接口的getFilter()方法,该方法将返回适配器中已过滤的列表项。 Take a look at the following question: 看看以下问题:

List View Filter Android 列表视图过滤Android

OR use SearchView 或使用SearchView

Try like this 试试这样吧

I changed the adapter class 我更改了适配器类

public class ApplicationAdapter extends ArrayAdapter<ApplicationInfo>  { 
    private List<ApplicationInfo> appsList = null; 
    private Context context; 
    private PackageManager packageManager;
    private List<ApplicationInfo> listOfApp;

    public ApplicationAdapter(Context context, int textViewResourceId, 
            List<ApplicationInfo> appsList) { 
        super(context, textViewResourceId, appsList); 
        this.context = context; 
        this.appsList = appsList;
        this.listOfApp = new ArrayList<ApplicationInfo>(); //Added here
        packageManager = context.getPackageManager();
        listOfApp.addAll(appsList);
    } 

    @Override
    public int getCount() { 
        return ((null != appsList) ? appsList.size() : 0); 
    } 

    @Override
    public ApplicationInfo getItem(int position) { 
        return ((null != appsList) ? appsList.get(position) : null); 
    } 

    @Override
    public long getItemId(int position) { 
        return position; 
    } 

    @Override
    public View getView(int position, View convertView, ViewGroup parent) { 
        View view = convertView; 
        if (null == view) { 
            LayoutInflater layoutInflater = (LayoutInflater) context 
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
            view = layoutInflater.inflate(R.layout.snippet_list_row, null); 
        } 

        ApplicationInfo data = appsList.get(position); 
        if (null != data) { 
            TextView appName = (TextView) view.findViewById(R.id.app_name); 
            TextView packageName = (TextView) view.findViewById(R.id.app_paackage); 
            ImageView iconview = (ImageView) view.findViewById(R.id.app_icon); 

            appName.setText(data.loadLabel(packageManager)); 
            packageName.setText(data.packageName); 
            iconview.setImageDrawable(data.loadIcon(packageManager)); 
        } 
        return view; 
    } 

 // Filter Class
    public void filter(String charText) {
        charText = charText.toLowerCase(Locale.getDefault());
        appsList.clear();
        if (charText.length() == 0) {
            appsList.addAll(listOfApp);
        } 
        else
        {
            for (ApplicationInfo ai : listOfApp) 
            {
                if (ai.loadLabel(packageManager).toString().toLowerCase(Locale.getDefault()).contains(charText)) 
                {
                    appsList.add(ai);
                }
            }
        }
        notifyDataSetChanged();
    }

}

and change in Activity 并改变活动

inputSearch.addTextChangedListener(new TextWatcher() {

            public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
               // I changed here to call filter method from Adapter class.
               String text =inputSearch.getText().toString().toLowerCase(Locale.getDefault());
                listadaptor.filter(text);
            }

            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                    int arg3) {
                // TODO Auto-generated method stub

            }

            public void afterTextChanged(Editable arg0) {
                // TODO Auto-generated method stub                          
            }
        });

Hope this help you. 希望这对你有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM