【问题标题】:How can I assign the default background to a Button? [duplicate]如何将默认背景分配给按钮? [复制]
【发布时间】:2012-07-13 13:01:43
【问题描述】:

可能重复:
How to remove ImageButton's standard background image?

我已将自定义背景设置为 Button。现在我想恢复此更改并再次显示Button 的默认背景。我该怎么做?

【问题讨论】:

  • 将你的问题标题复制到谷歌,第一个点击是this question。 -1 表示没有研究工作。
  • @alextsc 我想删除按钮的背景(并想设置默认背景)而不是图像按钮。如果我尝试在按钮的背景中设置空或透明图像,那么按钮就会消失。为什么??????
  • 你在某处将背景设置为 imageButton??
  • @AtulBhardwaj ImageButton 和 Button 小部件的代码相同(如果您在询问之前尝试过,您就会知道)。你也应该改写你的问题,我误解了它(显然和其他人一起)。我的印象是您想删除任何背景,包括默认背景,而不是您想将自定义背景重置为默认值。
  • @AkashG 首先这不是一个图像按钮,它是一个按钮。我要做的是首先更改按钮的背景,然后尝试将按钮设置为默认背景。跨度>

标签: android android-widget background-image


【解决方案1】:

通过编程,您可以执行类似的操作,

button.setBackgroundDrawable(null);
button.setBackgroundResource(0);

【讨论】:

  • 我的按钮通过设置 button.setBackgroundDrawable(null); 消失了
【解决方案2】:

您可以将android:background="@null" 用作您的Button。
或button.setBackgroundResource(0);
或button.setBackgroundDrawable(null);

【讨论】:

  • button.setBackgroundResources(0);这给出了错误,因为此方法未为按钮定义。和 button.setBackgroundDrawable(null);让我的按钮消失。
【解决方案3】:

一种解决方案是在将其设置为自定义背景之前记住您将哪个 Drawable 作为背景,例如保存在onCreate()。

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.your_layout);

    button = (Button) findViewById(R.id.yourbutton);
    defaultButtonBackgroundDrawable = button.getBackground();

    // set a custom background here, or somewhere else. 
    // Just make sure that the default one is saved before you modify it.
}

其中defaultButtonBackgroundDrawable 是您的活动的成员变量,button 保留对您的按钮的引用。这样你就可以很容易地恢复默认背景了

button.setBackgroundDrawable(defaultButtonBackgroundDrawable); 

【讨论】:

  • 感谢这个解决方案。它对我来说很好用但我发现了另一种也适用的解决方案 btn.setBackgroundDrawable(getResources().getDrawable(android.R.drawable.btn_default));
【解决方案4】:

终于解决了我的问题btn.setBackgroundDrawable(getResources().getDrawable(android.R.drawable.btn_default)); 这使我的按钮的背景与默认设置相同。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-21
    • 2013-06-26
    • 1970-01-01
    • 2020-12-24
    • 2013-02-17
    • 1970-01-01
    • 1970-01-01
    • 2014-11-03
    相关资源
    最近更新 更多