Skip to content Skip to sidebar Skip to footer

Select Position Of Cardview In Recyclerview And Change Fragment In Recyclerview

* EASY PART * At the moment I have set up a CardView inside a RecyclerView. What i need to do is to change the color of the 2nd cardview to yellow, and the 3rd cardview to red (At

Solution 1:

For the first part, you can just do the same thing you do with the titles. Add an array similar to this.

privatestaticString[] colors = newString[]{"#FFCE54", "#57ad48", "#c93e3c"};

Then access it like this.

recyclerViewHolder.cardView.setCardBackgroundColor( Color.parseColor( colors[i] ) );

You could also set the onClickListener inside the onBindViewHolder like this.

recyclerViewHolder.setOnClickListener(new View.OnClickListener() {       
    @Override
    public void onClick(View view) {
        getActivity().getSupportFragmentManager().beginTransaction().replace( R.id.recycler_view, new DataTabelFragment() ).commit();
    }
});

Or add it as an onItemTouchListener to your RecyclerView.

mRecyclerView.addOnItemTouchListener(newRecyclerView.OnItemTouchListener() {
        @OverridepublicbooleanonInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
            returnfalse;
        }

        @OverridepublicvoidonTouchEvent(RecyclerView rv, MotionEvent e) {
          getActivity().getSupportFragmentManager().beginTransaction().replace( R.id.recycler_view, newDataTabelFragment() ).commit();
        }

        @OverridepublicvoidonRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

        }
    });

Solution 2:

A short clarify :

  1. If you want to change only the first 3 cardviewcolors then you can simply check the position and do the job. But I suppose you want this to be a bit more customized, therefore you'll have to @Override getItemViewtypemethod of the adapter, and based on that you can show different views in the `Recyclerview. Sample

  2. Now, about the fragment you want to show from each cardview.. I see you are trying to do that from within the adapter. I suggest you do it from activity / fragment [RecyclerView Listener] (https://antonioleiva.com/recyclerview-listener/) properly implemented. In addition to this, you'll want to use add() method instead of replace for fragment transaction (this way you will have your list still shown below the added fragment, and you won't have to inflate or start the fragment again.

Post a Comment for "Select Position Of Cardview In Recyclerview And Change Fragment In Recyclerview"