Search code examples
javaandroidandroid-cardviewandroid-gridlayout

How to change the colour of a cardview when selected?clicked


I'm trying out card view instead of a button, I love the amount of info you can add to them. But I'm trying to make it so if they press the card it changes colour. I want it to change back once they release, so that it works in a similar way to my buttons.

I can get it so that it changes on click but it stay like that until the activity is destroyed.

This is the code I use for changing the colour at the moment:

public void setSingleEvent(GridLayout maingrid) {
    for (int i = 0; i < maingrid.getChildCount(); i++) {
        final CardView cardView = (CardView) maingrid.getChildAt(i);
        final int finalI = i;
        cardView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(mcontext, "Button: " + finalI, Toast.LENGTH_SHORT).show();
                cardView.setCardBackgroundColor(mcontext.getResources().getColor(R.color.buttonPressed));
                if (finalI == 0) {
                    mcontext.startActivity(new Intent(mcontext, Genre_Streaming.class));
                }
            }
        });

Solution

  • You can try using OnTouchListener with ACTION_DOWN and ACTION_UP to handle Press/Release events instead of OnClickListener.

    Modified Code:

    public void setSingleEvent(GridLayout maingrid) {
        for (int i = 0; i < maingrid.getChildCount(); i++) {
            final CardView cardView = (CardView) maingrid.getChildAt(i);
            final int finalI = i;
    
            cardView.setOnTouchListener(new OnTouchListener () {
              public boolean onTouch(View view, MotionEvent event) {
                if (event.getAction() == android.view.MotionEvent.ACTION_DOWN) {
                  Toast.makeText(mcontext, "Button: " + finalI, Toast.LENGTH_SHORT).show();
                  cardView.setCardBackgroundColor(mcontext.getResources().getColor(R.color.buttonPressed));
                  if (finalI == 0) {
                      mcontext.startActivity(new Intent(mcontext, Genre_Streaming.class));
                  }
                } else if (event.getAction() == android.view.MotionEvent.ACTION_UP) {
                  /* Reset Color */
                  cardView.setCardBackgroundColor(mcontext.getResources().getColor(R.color.red));
                }
                return true;
              }
            }
    }
    

    Link: http://developer.android.com/reference/android/view/MotionEvent.html#ACTION_UP