【问题标题】:Filter an Object in BaseAdapter在 BaseAdapter 中过滤对象
【发布时间】:2018-02-09 20:29:25
【问题描述】:

我是 Android 编程新手,我想在我的 Baseadapter 中创建一个自定义过滤器。

老实说,当我检查其他问题时,这有点令人困惑,因为它们大多使用 Arraylist。我已经创建了一个自定义视图 (getView),它将小象形图设置到我的 ListView 中。我已经尝试了很多方法来从 Arraylist 示例中实现这些自定义过滤器,但不知何故我陷入了困境。

如果有人可以至少给我一些关于带有对象的自定义过滤器的方向,那将非常有帮助

cryptoListAdapter.java

public class cryptoListAdapter extends BaseAdapter {
    private Context context;
    LayoutInflater mInlfater;
    ArrayList<HashMap<String,String>> currencyList;
    TextView name;



    // Constructor
    public cryptoListAdapter(Context context,ArrayList<HashMap<String,String>> currencyList)
    {
        mInlfater = LayoutInflater.from(context);
        this.currencyList = currencyList;
    }





    @Override
    public int getCount() {
        return currencyList.size();

    }

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

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


    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        cryptoPicto cp = new cryptoPicto();

        View newView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_crypto_items, null);
        name = (TextView) newView.findViewById(R.id.name);
        TextView symbol = (TextView) newView.findViewById(R.id.symbol);
        ImageView image_list_icon = (ImageView)newView.findViewById(cryptopicto);
        //cp.createFinalFileName(name);

        HashMap<String, String> map;
        map = currencyList.get(position);
        name.setText(map.get("name"));
        symbol.setText(map.get("symbol"));
        Picasso.with(newView.getContext()).load(map.get("cryptopicto")).into(image_list_icon);


        return newView;
    }

currencyTableView.java

    public class currencyTableView extends AppCompatActivity {

    private String TAG = currencyTableView.class.getSimpleName();

    private ProgressDialog pDialog;
    private ListView lv;
    private SearchView sv;
    private ImageView im;
    private static String url = "https//myURLToJSON";
    Context context;
    cryptoListAdapter adapter;

    ArrayList<HashMap<String, String>> currencyList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_currency_table_view);
        sv = (SearchView) findViewById(R.id.search_currency);

        currencyList = new ArrayList<>();

        lv = (ListView) findViewById(R.id.list);
        im = (ImageView) findViewById(R.id.cryptopicto);


        new GetCurrencies().execute();



    }


    // URL to get currencies JSON


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

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(currencyTableView.this);
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            databasehandler sh = new databasehandler();
            cryptoPicto cp = new cryptoPicto();

            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(url);

            Log.e(TAG, "Response from url: " + jsonStr);

            if (jsonStr != null) {
                try {
                    JSONArray jsonArray = new JSONArray(jsonStr);


                    // looping through currencies
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject c = jsonArray.getJSONObject(i);

                        String name = c.getString("name");
                        String symbol = c.getString("symbol");
                        Double price_usd = c.getDouble("price_usd");
                        Double price_eur = c.getDouble("price_eur");
                        Double price_btc = c.getDouble("price_btc");
                        Double volume_eur = c.getDouble("volume_eur");
                        Double market_cap_usd = c.getDouble("market_cap_usd");
                        Double percent_change_1h = c.getDouble("percent_change_1h");
                        Double percent_change_24h = c.getDouble("percent_change_24h");
                        Double percent_change_7d = c.getDouble("percent_change_7d");


                        // tmp hash map for single currency
                        HashMap<String, String> currency = new HashMap<>();

                        // create Path to picto Filename

                        cp.createFinalFileName(name);

                        // adding each child node to HashMap key => value
                        currency.put("cryptopicto", cp.getFinalFileName());
                        currency.put("name", name);
                        currency.put("symbol", symbol);

                        // adding currency to currencyList
                        currencyList.add(currency);

                    }
                } catch (final JSONException e) {
                    Log.e(TAG, "Json parsing error: " + e.getMessage());
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(),
                                    "Json parsing error: " + e.getMessage(),
                                    Toast.LENGTH_LONG)
                                    .show();
                        }
                    });

                }
            } else {
                Log.e(TAG, "Couldn't get json from server.");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Couldn't get json from server. Check LogCat for possible errors!",
                                Toast.LENGTH_LONG)
                                .show();
                    }
                });

            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();
            /**
             * Updating parsed JSON data into ListView
             * */



            adapter = new cryptoListAdapter(
                            currencyTableView.this, currencyList) {

                    };

            lv.setAdapter(adapter);

            sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
                @Override
                public boolean onQueryTextSubmit(String query) {
                    return false;
                }

                @Override
                public boolean onQueryTextChange(String currencyList) {

                    adapter.getFilter().filter(currencyList);
                    return false;
                }
            });
        }
    }
}

在此先感谢 :)

【问题讨论】:

    标签: java android xml android-layout filter


    【解决方案1】:

    让你的 BaseAdapder 实现 Filterable 然后添加

    List<HashMap<String,String>> mOriginalValues;
    

    之后

    ArrayList<HashMap<String,String>> currencyList;
    

    在您的适配器类中

    然后在底部的右大括号“}”之前添加这个方法

    @Override
    public Filter getFilter() {
    
        Filter filter = new Filter() {
    
            @SuppressWarnings("unchecked")
            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {
    
            currencyList = (ArrayList<HashMap<String,String>>) results.values; 
    
                notifyDataSetChanged();
            }
    
            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                FilterResults results = new FilterResults(); 
                ArrayList<HashMap<String, String>> FilteredArrList = new ArrayList<HashMap<String, String>>();
    
                if (mOriginalValues == null) {
                    mOriginalValues = new ArrayList<HashMap<String, String>>(currencyList); // saves
    
                }
    
    
                if (constraint == null || constraint.length() == 0) {
    
                    // set the Original result to return
                    results.count = mOriginalValues.size();
                    results.values = mOriginalValues;
                } else {
                    Locale locale = Locale.getDefault();
                    constraint = constraint.toString().toLowerCase(locale);
                    for (int i = 0; i < mOriginalValues.size(); i++) {
                           HashMap<String, String> currency = mOriginalValues.get(i);
                        String data = currency.get("name");
                        if (data.toLowerCase(locale).startsWith(constraint.toString())) {
    
                            FilteredArrList.add(currency);
                        }
    
                    }
                    // set the Filtered result to return
                    results.count = FilteredArrList.size();
                    results.values = FilteredArrList;
    
                }
                return results;
            }
        };
        return filter;
    }
    

    如果有帮助请告诉我

    【讨论】:

    • 谢谢!看起来很合理,我一下班就试试!
    • 如果有帮助的话。将答案标记为正确并点赞
    • 这对我很有帮助!谢谢!我也明白了:)
    • 很高兴知道:)
    猜你喜欢
    • 2011-10-17
    • 1970-01-01
    • 2013-03-28
    • 2012-09-09
    • 2017-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多