Button - Change background color on click

前端 未结 5 642
再見小時候
再見小時候 2021-02-03 10:48

I have 8 buttons in my activity. What I am looking for is, The buttons have a default background and when a button is clicked, the background color should change to some other c

5条回答
  •  被撕碎了的回忆
    2021-02-03 11:10

    Create a shape named button_pressed.xml

    
    
        
    
        
    
        
    
    
    

    Suppose, you have two buttons whose IDs are R.id.btn and R.id.btn1

    
    
        

    Write the onClick() method which will allow you to retain the changed color until another button is pressed.

    Button button;
    
    public void onClick(View v) {
    
        Drawable dr = getResources().getDrawable(R.drawable.button_pressed);
        dr.setColorFilter(Color.parseColor("#FF0000"), PorterDuff.Mode.SRC_ATOP);
    
        switch (v.getId()) {
        case R.id.btn:
    
            if (button == null) {
                button = (Button) findViewById(v.getId());
            } else {
                button.setBackgroundResource(R.drawable.button_pressed);
                button = (Button) findViewById(v.getId());
            }
            button.setBackgroundDrawable(dr);
    
            break;
    
        case R.id.btn2:
            if (button == null) {
                button = (Button) findViewById(v.getId());
            } else {
                button.setBackgroundResource(R.drawable.button_pressed);
                button = (Button) findViewById(v.getId());
            }
            button.setBackgroundDrawable(dr);
    
            break;
    
        default:
            break;
        }
    }
    

    I think, now you will get What you wanted to do.

提交回复
热议问题