Java – How do I change the color of the card View when selected? Click

How do I change the color of the card View when selected? Click… here is a solution to the problem.

How do I change the color of the card View when selected? Click

I’m trying to use a card View instead of a button, and I like the amount of information you can add to it. But I’m trying to do it, and if they press the card, it changes color. I want it to go back to where it is after they are released so that it works in a similar way to my buttons.

I can get it so that it changes on click, but it stays that way until the activity is destroyed.

This is the code I use now to change the color :

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

Instead of OnClickListener, you can try using OnTouchListener with ACTION_DOWN and ACTION_UP to handle Press/Release events.

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

Related Problems and Solutions