安卓如何更改图像按钮的背景?

4
我无法更改图像按钮的背景图片。这是我当前尝试使用的代码:
ImageButton imgButton = (ImageButton) findViewById(R.id.showSportsButton);
imgButton.setBackgroundResource(R.drawable.tab2_selected);

然而,似乎是将新图像放在旧图像的顶部,导致我有两个图像重叠在一起。有人知道为什么会这样吗?

我猜你需要使用从ImageView继承的.setImageResource方法。 - zapl
please add imgButton.setImageResource(null); imgButton.setImageResource(R.drawable. tab2_selected); - dipali
旧图像是什么 - 默认的那个,也就是灰色的(例如,根据主题而定)图像的意思? - g00dy
4个回答

10

要解决这个问题,您需要实现:

imgButton.setImageResource(R.drawable. tab2_selected);

1
使用此方法:

imgButon.setBackground(getActivity().getDrawable(R.drawable.your_icon));

0
在xml文件中,写入:<Button>android:backgroud="@drawable/your_file"

0

确保您在同一个活动中。如果您要更改不同活动的背景,请先创建构造函数,然后使用对象来更改按钮。

Activity obj= new activity();
obj.imgButton.setBackgroundResource(R.drawable.tab2_selected);

同时还要检查,如果您仅使用findviewbyid,则oncreate()方法必须具有void返回类型。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接