【问题标题】:Change button android:background to different drawable将按钮 android:background 更改为不同的可绘制对象
【发布时间】:2012-10-20 15:30:14
【问题描述】:

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

在这里,我有许多彩色按钮,单击它们时,颜色会变为一系列不同的颜色。

有很多按钮定义例如:

<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 使用代码将上面的示例更改为黄色,例如,当单击按钮时。

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

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

    }

我正在使用自定义按钮样式来定义按钮颜色:

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

现在我只需要弄清楚如何将按钮从橙色更改为黄色。然后,我可以添加逻辑以在应用需要时更改颜色。

非常感谢您的帮助。

【问题讨论】:

    标签: android button background drawable


    【解决方案1】:

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

      v.setBackgroundResource(R.drawable.yellow_button);
    

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

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

    【讨论】:

    • 哇。什么社区!发现。 onClick 方法位于我需要更改的同一个 Button 上,因此您的第一个解决方案第一次起作用。现在,如果单击,所有按钮都会变黄!我现在可以按逻辑进行。谢谢。
    • 当我将活动留给另一个活动并返回第一个活动时,背景不会恢复为原始可绘制对象。
    • @SiKni8 对于你想要的效果,你应该使用
    【解决方案2】:
    Button btn = (Button) findViewById(R.id.button17);
    btn.setBackground(this.getResources().getDrawable(R.drawable.yellow_button));
    

    试试这个。

    【讨论】:

    • Resources 类型的 getDrawable(int) 方法已弃用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-03
    • 2017-01-13
    • 1970-01-01
    • 1970-01-01
    • 2015-12-15
    • 1970-01-01
    相关资源
    最近更新 更多