将按钮 android:background 更改为不同的可绘制对象 [英] Change button android:background to different drawable

查看:22
本文介绍了将按钮 android:background 更改为不同的可绘制对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Android 和 Java 的新手,但我成功地自学并在 stackoverflow 上找到了大多数问题的答案,而无需提问.直到现在……

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.

有很多按钮定义例如:

<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" />

有人可以告诉我如何更改 android:background 使用代码将上面的示例更改为黄色,例如,当单击按钮时.

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.

在下面的代码中,clickedButton 是我需要更改背景的按钮的 ID.

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.

非常感谢您的帮助.

推荐答案

我假设您发布的 onClick 方法与您尝试更改其背景的 Button 相同.使用此代码.

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);

如果onClick不是同一个按钮的方法那么,使用

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

  findViewById(R.id.button17).setBackgroundResource(R.drawable.yellow_button);

这篇关于将按钮 android:background 更改为不同的可绘制对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆