Change button android:background to different draw

2019-04-04 08:19发布

I am new to Android and Java but have managed to teach myself and find most answers to questions on stackoverflow without needing to ask questions. Until now....

Here goes, I have many colored buttons which, when clicked, change color to a range of different colors.

There are many buttons defined for example as:

<Button
   android:id="@+id/button17"
   android:layout_width="0dp"
   android:layout_height="fill_parent"
   android:layout_weight="1"
   android:background="@drawable/orange_button"
   android:gravity="center"
   android:onClick="onClick" />

Could someone please advise me how to change the android:background using code to change the above example to yellow, for example, when the button is clicked.

In the code below clickedButton is the ID of the button for which I need to change the background.

public void onClick(View v) {
    int id=v.getId();
    String clickedButton = getResources().getResourceEntryName(id);

    Change button to Yellow here??

    // Temporary code below to check which button was pressed
    // and convert its number to an integer to eventually access an array

    final TextView tvGameTimer = (TextView) findViewById(R.id.tvGameTimer);
    int buttonNumber = Integer.parseInt(clickedButton.substring(6,8));
    tvGameTimer.setText("" + buttonNumber);

    }

I am using custom button styles to define the button colors:

res/drawable/yellow_button.xml
res/drawable/blue_button.xml
res/drawable/red_button.xml
res/drawable/orange_button.xml
res/drawable/green_button.xml

For now I just need to work out how to change the button from Orange to Yellow. I can then add the logic to change the colors as and when the app requires.

Many thanks for any help.

2条回答
时光不老,我们不散
2楼-- · 2019-04-04 08:37

I am supposing that the onClick method you post is of the same Button whose background you are trying to change. Use this code.

  v.setBackgroundResource(R.drawable.yellow_button);

If onClick is not the method of the same button then, use

  findViewById(R.id.button17).setBackgroundResource(R.drawable.yellow_button);
查看更多
我想做一个坏孩纸
3楼-- · 2019-04-04 08:39
Button btn = (Button) findViewById(R.id.button17);
btn.setBackground(this.getResources().getDrawable(R.drawable.yellow_button));

Try this.

查看更多
登录 后发表回答