how to highlight the selected Item of Recycler View?

前端 未结 8 1312
执念已碎
执念已碎 2020-11-28 03:02

I have a Recycler View with the Images loaded from the Internal Storage. I want to Highlight the selected item when clicked. I tried a lot of thing but it was not working. A

8条回答
  •  一向
    一向 (楼主)
    2020-11-28 03:33

    I have tried several ways for hours and here is the two solutions I came out with. Both solutions assume I have my RecyclerView declared as follows:

    activity.xml

    
    

    Nothing special here, just a regular RecyclerView declaration. Now let's see the other files, starting with the most easy and viable solution.

    First solution (XML only)

    layout/item.xml

    The two important attributes here in the item's root ViewGroup are background and clickable.

    
    
    
        ...
    
    
    

    drawable/selector_item.xml

    
    
    
        
    
        
    
    
    

    Second solution (XML + Java)

    item.xml

    No background nor clickable attribute here.

    
    
        ...
    
    
    

    Adapter.java

    public class Adapter extends RecyclerView.Adapter {
        public class ViewHolder extends RecyclerView.ViewHolder {
            public ViewHolder(View itemView) {
                super(itemView);
    
                itemView.setOnTouchListener(itemTouchListener);
            }
        }
    
        ...
        private View.OnTouchListener itemTouchListener = new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        v.setBackgroundResource(R.drawable.background_item_event_pressed);
                        break;
                    case MotionEvent.ACTION_CANCEL:
                        // CANCEL triggers when you press the view for too long
                        // It prevents UP to trigger which makes the 'pressed' background permanent which isn't what we want
                    case MotionEvent.ACTION_OUTSIDE:
                        // OUTSIDE triggers when the user's finger moves out of the view
                    case MotionEvent.ACTION_UP:
                        v.setBackgroundResource(R.drawable.background_item_event);
                        break;
                    default:
                        break;
                }
    
                return true;
            }
        };
    
        ...
    }
    

    I highly recommend using the first solution as it's easier to maintain and more powerful as it also allows you to add ripple effects (in the drawable/background_item... XML files), which I believe isn't possible with solution 2.

提交回复
热议问题