Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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));
                }
            }
        });
like image 304
markharrop Avatar asked Oct 17 '25 17:10

markharrop


1 Answers

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

like image 91
user2004685 Avatar answered Oct 19 '25 09:10

user2004685



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!