【问题标题】:filtration alphabetically with ListAdapter using listview in android app在 Android 应用程序中使用 ListView 按字母顺序过滤 ListAdapter
【发布时间】:2015-08-25 15:14:33
【问题描述】:

我正在开发一个安卓应用程序。该应用在 Listview 中使用 json 和 ListAdpter 绑定数据。现在我想根据用户在搜索框中写信来过滤这些数据。我试图这样做,但由于列表视图中绑定了多个数据,我不知道如何过滤它。以下是我的代码:

private void getdatalatlog(double latitude, double longitude) {
    // TODO Auto-generated method stub
    //value=5;
    String url = "http://bizzcoder.co.in/php/comments.php?latitude='"+latitude+"'&longitude='"+longitude+"'&value='"+value+"'";
    aq.progress(R.id.progressBar1).ajax(url, JSONObject.class, this,"jsonCallback");

}


public void jsonCallback(String url, JSONObject json, AjaxStatus status) {  


    if (json != null) { 

    List<String> city = new ArrayList<String>();
    mCommentList = new ArrayList<HashMap<String, String>>();

        Gson gson = new GsonBuilder().create();
        try {

            JSONArray jsonResponse = json.getJSONArray("posts");
            city = gson.fromJson(jsonResponse.toString(),List.class);
            for (int i = 0; i < jsonResponse.length(); i++) {
                JSONObject c = jsonResponse.getJSONObject(i);       

                String title = c.getString(TAG_TITLE);
                String content = c.getString(TAG_MESSAGE);
                String username = c.getString(TAG_USERNAME);
                String lat = c.getString(TAG_LATITUDE);
                String log = c.getString(TAG_LONGITUDE);
                String cont = c.getString(TAG_CONTACT);

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

                map.put(TAG_TITLE, title);
                map.put(TAG_MESSAGE, content);
                map.put(TAG_USERNAME, username);
                map.put(TAG_LATITUDE, lat);
                map.put(TAG_LONGITUDE, log);
                map.put(TAG_CONTACT, cont);
                    // adding HashList to ArrayList
            mCommentList.add(map);


            }
        } 
        catch (JSONException e) {

            Toast.makeText(aq.getContext(), "Error in parsing JSON", Toast.LENGTH_LONG).show();
        }
        catch (Exception e) {
            Toast.makeText(aq.getContext(), "Something went wrong", Toast.LENGTH_LONG).show();
        }

        ListAdapter adapter = new SimpleAdapter(this, mCommentList,
                R.layout.single_post, new String[] { TAG_TITLE,TAG_USERNAME ,TAG_CONTACT ,TAG_MESSAGE ,TAG_LATITUDE , TAG_LONGITUDE 
                        }, new int[] { R.id.shop_name,R.id.address,R.id.contact,R.id.distance,R.id.latitude,R.id.longitude });


        setListAdapter(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
                Shopdetail.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                          
            }
        });

        ListView lv = getListView();    
        lv.setOnItemClickListener(new OnItemClickListener() {


            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {

                Intent intent = new Intent();
                 Bundle b = new Bundle();


                 String name= ((TextView) view.findViewById(R.id.shop_name)).getText().toString()+" , "+((TextView) view.findViewById(R.id.contact)).getText().toString();

                 String lati= ((TextView) view.findViewById(R.id.latitude)).getText().toString();

                 String longi= ((TextView) view.findViewById(R.id.longitude)).getText().toString();

                 b.putString("shop",name);
                 b.putString("lati",lati);
                 b.putString("long",longi);
                intent.setClass(Shopdetail.this, Mapview.class);
                intent.putExtras(b);
                startActivity(intent);
            }
        });
} 
     }

listview 中绑定了多个详细信息,例如商店名称、联系电话、地址等。我只想按商店名称过滤它。但我在 getfilter() 方法下面划了红线。

【问题讨论】:

    标签: android listview android-listview listadapter


    【解决方案1】:

    其实我是这样做的(EditText 在工具栏上,但它可以在你想要的任何地方):

                inputSearch = (EditText) findViewById(R.id.inputSearch);
                inputSearch.addTextChangedListener(new TextWatcher() {
    
                    @Override
                    public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
                        // When user changed the Text
                        adapter.getFilter().filter(cs.toString());
                    }
    
                    @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
                    }
                });
    

    编辑:

    要过滤自定义 Base 适配器,您必须将其与适配器放在类中:

        List<Fanfic> fanfics;
        private List<Fanfic>filteredData = null;
        private ItemFilter mFilter = new ItemFilter();
    

    您需要 2 个列表 - 第一个包含所有数据,第二个包含过滤数据

    在所有方法中,您必须使用过滤数据(在构造函数中,getCount,getItem,getItemId),而不是过滤数据,您只需填写构造函数。

    这里是 ItemFilter 类:

    private class ItemFilter extends Filter {
            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
    
                String filterString = constraint.toString().toLowerCase();
    
                FilterResults results = new FilterResults();
    
                final List<Fanfic> list = fanfics;
    
                int count = list.size();
                final ArrayList<Fanfic> nlist = new ArrayList<Fanfic>(count);
    
                String filterableString ;
    
                for (int i = 0; i < count; i++) {
                    filterableString = list.get(i).getName();
                    if (filterableString.toLowerCase().startsWith(filterString)) {
                        nlist.add(list.get(i));
                    }
                }
    
                results.values = nlist;
                results.count = nlist.size();
    
                return results;
            }
    
            @SuppressWarnings("unchecked")
            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {
                filteredData = (ArrayList<Fanfic>) results.values;
                notifyDataSetChanged();
            }
    
        }
    

    并将此方法添加到您的适配器:

    public Filter getFilter() {
        return mFilter;
    }
    

    最后一件事,你必须实现 Filterable。

    【讨论】:

    • 实际上我在适配器中遇到了错误,因为我使用了 listadpter 和 getfilter 方法给 listadpter 带来了错误。
    • 我不确定是否可以使用 ListAdapter。为什么不使用 castom BaseAdapter?要在不超过 5 分钟内获得与使用 ListAdapter 相同的结果。我将为您编辑我的帖子,其中包含您需要放入过滤器适配器的代码
    • 我想在listview中绑定多个数据,所以我使用了ListAdapter。我无法改变它。
    • 自定义适配器绑定数据有什么问题?以任何方式将它们绑定在 List 中,然后通知数据已更改。
    • 无论如何,如果您确定必须使用 ListAdapter,请尝试重载 ListAdapter 并在其中添加过滤器,就像我为您写的 BaseAdapter 一样
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-09
    • 2012-09-27
    • 2021-12-23
    • 2019-02-08
    • 1970-01-01
    相关资源
    最近更新 更多