Recyclerview过滤器选择Filteres之后的前一个元素数据

时间:2017-10-31 18:35:25

标签: java android android-recyclerview

我使用onQueryTextChange方法过滤我的recyclerview数据,过滤器工作正常,但是当我在过滤器后点击一个元素时,它仍然会拾取放在过滤器之前的元素。有人可以指出我在这里做错了什么。

MainActivity.java

    public class MainActivity extends AppCompatActivity implements SearchView.OnQueryTextListener
 {

    List<DataAdapter> DataAdapterClassList;

    RecyclerView recyclerView;

     EditText etSearch;

    RecyclerView.LayoutManager recyclerViewlayoutManager;

    RecyclerViewAdapter recyclerViewadapter;

    ProgressBar progressBar;

    JsonArrayRequest jsonArrayRequest;

    ArrayList<String> BankNames;

    RequestQueue requestQueue;

    String HTTP_SERVER_URL = "http://hiddenforsecurity.com?method=apiTest";

    View ChildView;

    int RecyclerViewClickedItemPOS;

    LinearLayout lyt, icicBtn, hdfcBtn, axisBtn, sbiBtn, pnbBtn, yesBtn;

     private static int firstVisibleInListview;




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


        DataAdapterClassList = new ArrayList<>();

        BankNames = new ArrayList<>();

        recyclerView = (RecyclerView) findViewById(R.id.recyclerView1);

        progressBar = (ProgressBar) findViewById(R.id.progressBar1);

        recyclerView.setHasFixedSize(true);

        recyclerViewlayoutManager = new LinearLayoutManager(this);

        recyclerView.setLayoutManager(recyclerViewlayoutManager);

        lyt = (LinearLayout) findViewById(R.id.Layout1);

        final Intent go = new Intent(MainActivity.this, StateList.class);


        icicBtn = (LinearLayout) findViewById(R.id.icicBtn);
        hdfcBtn = (LinearLayout) findViewById(R.id.hdfcBtn);
        axisBtn = (LinearLayout) findViewById(R.id.axisBtn);
        sbiBtn = (LinearLayout) findViewById(R.id.sbiBtn);
        pnbBtn = (LinearLayout) findViewById(R.id.pnbBtn);
        yesBtn = (LinearLayout) findViewById(R.id.yesBtn);

        final Intent i = new Intent(this, StateList.class);


        // JSON data web call function call from here.
        JSON_WEB_CALL();

        //RecyclerView Item click listener code starts from here.
        recyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {

            GestureDetector gestureDetector = new GestureDetector(MainActivity.this, new GestureDetector.SimpleOnGestureListener() {

                @Override
                public boolean onSingleTapUp(MotionEvent motionEvent) {

                    return true;
                }

            });

            @Override
            public boolean onInterceptTouchEvent(RecyclerView Recyclerview, MotionEvent motionEvent) {

                ChildView = Recyclerview.findChildViewUnder(motionEvent.getX(), motionEvent.getY());

                if (ChildView != null && gestureDetector.onTouchEvent(motionEvent)) {

                    //Getting RecyclerView Clicked item value.
                    RecyclerViewClickedItemPOS = Recyclerview.getChildAdapterPosition(ChildView);
                    Toast.makeText(MainActivity.this, BankNames.get(RecyclerViewClickedItemPOS), Toast.LENGTH_SHORT).show();
                    //Printing RecyclerView Clicked item clicked value using Toast Message.
                    //i.putExtra("selectedbank", BankNames.get(RecyclerViewClickedItemPOS));
                    //startActivity(i);

                }

                return false;
            }

            @Override
            public void onTouchEvent(RecyclerView Recyclerview, MotionEvent motionEvent) {

            }

            @Override
            public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

            }
        });

        icicBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                go.putExtra("selectedbank", "ICICI BANK LIMITED");
                startActivity(go);
            }
        });

        axisBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                go.putExtra("selectedbank", "AXIS BANK");
                startActivity(go);
            }
        });

        hdfcBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                go.putExtra("selectedbank", "HDFC BANK");
                startActivity(go);
            }
        });

        sbiBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                go.putExtra("selectedbank", "STATE BANK OF INDIA");
                startActivity(go);
            }
        });
        pnbBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                go.putExtra("selectedbank", "PUNJAB NATIONAL BANK");
                startActivity(go);
            }
        });
        yesBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                go.putExtra("selectedbank", "YES BANK");
                startActivity(go);
            }
        });
    }


    public void JSON_WEB_CALL(){

        progressBar.setVisibility(View.VISIBLE);

        jsonArrayRequest = new JsonArrayRequest(HTTP_SERVER_URL,

                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {

                        JSON_PARSE_DATA_AFTER_WEBCALL(response);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });

        requestQueue = Volley.newRequestQueue(this);

        requestQueue.add(jsonArrayRequest);
    }

    public void JSON_PARSE_DATA_AFTER_WEBCALL(JSONArray array){

        for(int i = 0; i<array.length(); i++) {

            DataAdapter GetDataAdapter2 = new DataAdapter();

            JSONObject json = null;
            try {
                json = array.getJSONObject(i);


                GetDataAdapter2.setBankName(json.getString("BANK"));

                //Adding subject name here to show on click event.
                BankNames.add(json.getString("BANK"));

            }
            catch (JSONException e)
            {

                e.printStackTrace();
            }

            DataAdapterClassList.add(GetDataAdapter2);

        }

        progressBar.setVisibility(View.GONE);

        recyclerViewadapter = new RecyclerViewAdapter(DataAdapterClassList, this);

        recyclerView.setAdapter(recyclerViewadapter);

    }

     @Override
     public boolean onCreateOptionsMenu(Menu menu) {
         getMenuInflater().inflate(R.menu.menu_search, menu);

         MenuItem item = menu.findItem(R.id.action_search);
         SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);

         searchView.setOnQueryTextListener(this);

         return super.onCreateOptionsMenu(menu);
     }

     @Override
     public boolean onQueryTextSubmit(String query) {
         return false;
     }

     @Override
     public boolean onQueryTextChange(String newText) {


         final List<DataAdapter> filteredModelList = filter(DataAdapterClassList, newText);
         if (filteredModelList.size() > 0) {
             recyclerViewadapter.setFilter(filteredModelList);
             return true;
         } else {
             Toast.makeText(MainActivity.this, "Not Found", Toast.LENGTH_SHORT).show();
             return false;
         }

     }

     private List<DataAdapter> filter(List<DataAdapter> models, String query) {
         query = query.toLowerCase();

         final List<DataAdapter> filteredModelList = new ArrayList<>();
         for (DataAdapter model : models) {
             final String text = model.getBankName().toLowerCase();
             if (text.contains(query)) {
                 filteredModelList.add(model);
             }
         }

         recyclerViewadapter = new RecyclerViewAdapter(filteredModelList, MainActivity.this);
         recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
         recyclerView.setAdapter(recyclerViewadapter);
         recyclerViewadapter.notifyDataSetChanged();
         return filteredModelList;
     }

 } 

RecyclerviewAdapter.java

    public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {

    Context context;

    public DataAdapter dataAdapter;

    List<DataAdapter> dataAdapters;

    public RecyclerViewAdapter(List<DataAdapter> getDataAdapter, Context context){

        super();

        this.dataAdapters = getDataAdapter;
        this.context = context;
    }



    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview, parent, false);

        ViewHolder viewHolder = new ViewHolder(view);

        return viewHolder;
    }


    @Override
    public void onBindViewHolder(ViewHolder viewHolder, int position) {

        dataAdapter =  dataAdapters.get(position);

        viewHolder.TextViewName.setText(dataAdapter.getBankName());

    }

    @Override
    public int getItemCount() {

        return dataAdapters.size();
    }

    class ViewHolder extends RecyclerView.ViewHolder{

        public TextView TextViewName;

        public ViewHolder(View itemView) {
            super(itemView);
            TextViewName = (TextView) itemView.findViewById(R.id.TextViewCard) ;

        }
    }

    public void setFilter(List<DataAdapter> bankNames) {
        dataAdapters = new ArrayList<>();
        dataAdapters.addAll(bankNames);
        notifyDataSetChanged();
    }


} 

请查看这些屏幕截图,以便更好地了解我的查询。

当我在过滤前点击某个项目时,Toast会显示正确的数据。 Unfiltered Screenshot

当我在过滤后点击某个项目时,Toast仍然显示上面屏幕截图中的数据,它应该显示HDFC BANK。Filtered Screenshot

1 个答案:

答案 0 :(得分:0)

这是因为您要在列表视图中更改数据集,但稍后在Toast中更改为BankNames,这是不同的数据集。

在您的示例列表中,由于过滤器而导致ony 1元素。当您单击它时,单击的索引实际上将为0,而不是您需要的x,稍后您将从BankNames中选择0索引库而不是从筛选结果集中选择。

为了解决问题,请使用相同的数据集进行列表视图和数据提取。 您只需创建包含当前已过滤结果的filteredBankNames集合,然后将其传递到列表视图即可。同时,在点击事件中,从filteredBankNames中挑选银行名称以及BankNames

例如:

     // make this not final local variable, but a field in activity so you can remember filtered items
     final List<DataAdapter> filteredModelList = filter(DataAdapterClassList, newText);
     if (filteredModelList.size() > 0) {
         recyclerViewadapter.setFilter(filteredModelList);
         return true;
     } else {

Toast

 Toast.makeText(MainActivity.this, filteredModelList.get(RecyclerViewClickedItemPOS), Toast.LENGTH_SHORT).show();