简体   繁体   English

如何在Android中更改ImageButton的背景图像

[英]How to change background image of a ImageButton in android

I am facing a situation in which- 1.First I have to set the background image of a ImageButton to a default image. 我面临的情况是:1.首先,我必须将ImageButton的背景图像设置为默认图像。 2.Now at runtime based on some condition I have to change the background image of that ImageButton to some other image. 2.现在在运行时基于某种条件,我必须将ImageButton的背景图像更改为其他图像。

I have tried this but it doesn't work and the background image remains to default image and doesn't change. 我已经尝试过了,但是它不起作用,背景图像仍然是默认图像,并且没有变化。

 btn.invalidateDrawable((Drawable)getResources().getDrawable(R.drawable.info));
                btn.setBackgroundDrawable((Drawable)getResources().getDrawable(R.drawable.infonewred));

How can I achieve this goal. 我怎样才能实现这个目标。

您是否尝试过btn.setBackgroundResource(R.drawable.infonewred)

I know that's old but i got the solution as i'm also was searching for that, the correct answer is to use setImageResource , so the code will be like that: 我知道那是旧的,但是我也正在寻找解决方案,因为我也在寻找那个,正确的答案是使用setImageResource ,所以代码将像这样:

btn.invalidateDrawable(getResources().getDrawable(R.drawable.info));
btn.setImageResource(R.drawable.infonewred);

Try the method setImageResource 尝试方法setImageResource

Ex: 例如:

if(someCondition()){
   btn.setImageResource(R.drawable.info);
} else {
   btn.setImageResource(R.drawable.infonewred);
}

I suggest you set the "default" Background directly in your XML-Layout-File via android:background . 我建议您通过android:background直接在XML-Layout-File中设置“默认” android:background If you have to change the Background in Runtime just use btn.setBackgroundResource(R.drawable.imagename); 如果必须在运行时中更改背景,只需使用btn.setBackgroundResource(R.drawable.imagename);

in activity file you can write btn.setBackgroundResource(R.drawable.sliderr); 在活动文件中,您可以编写btn.setBackgroundResource(R.drawable.sliderr);

OR 要么

in your xml layout file you can add one extra line to you button xml code android:src="@drawable/sliderr" 在您的xml布局文件中,您可以向您添加额外的一行按钮xml代码android:src =“ @ drawable / sliderr”

Just try following code to change at runtime and for default view set background property in layout xml: 只需尝试以下代码即可在运行时进行更改,并针对布局xml中的默认视图集背景属性进行更改:

if(yourCondition)
    btn.setBackgroundResource(R.drawable.infonewred);

since you haven't provided xml, i am guessing you are providing src to imageButton.. so to change the source of the image , what you are doing is changing the image background which will not be visible since it is the source which will be visible to you.. so to change source.. 由于您没有提供xml,所以我想您正在为sButton提供src ..因此,要更改图像的来源,您正在做的是更改将不可见的图像背景,因为它是对您可见..因此更改源..

do this. 做这个。

btn.setImageDrawable()

rather than.. 而不是..

btn.setBackgroundDrawable()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM