如何将默认背景分配给按钮?

问题描述:

可能重复:
How to remove ImageButton's standard background image?如何将默认背景分配给按钮?

我设置一个自定义背景的Button。现在我想恢复此更改并再次显示Button的默认背景。我怎样才能做到这一点?

+1

复制你的问题的标题到谷歌,第一主打为[这个问题](http://stackoverflow.com/questions/5457138/how-to-很轻松地恢复默认的背景除去-imagebuttons规格的背景图像)。 -1没有研究工作。 – 2012-07-13 13:05:27

+0

请发表您的按钮的xml – AkashG 2012-07-13 13:05:41

+0

@alextsc我想删除按钮的背景(并且要设置默认背景)而不是图像按钮。如果我尝试在Button的背景中设置空或透明图像,则Button将消失。为什么?????? – 2012-07-13 13:13:22

一个解决方案就是在您将其设置为自定义之前记住哪个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); 
+3

感谢您的解决方案。它对我来说工作正常但我发现了另一种解决方案,它也可以工作btn.setBackgroundDrawable(getResources()。getDrawable(android.R.drawable.btn_default)); – 2012-07-13 13:41:48

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

+0

button.setBackgroundResources(0);这是错误的,因为这个方法对于按钮是未定义的。和button.setBackgroundDrawable(null);使我的按钮消失。 – 2012-07-13 13:19:22

通过编程,你可以这样做,

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

通过设置button.setBackgroundDrawable(null),我的按钮变得消失; – 2012-07-13 13:16:42

最后我得到了我的问题btn.setBackgroundDrawable(getResources().getDrawable(android.R.drawable.btn_default)); 这使我的按钮的背景,因为它在默认情况下的解决方案。