简体   繁体   English

Android更改图像按钮背景

[英]android change image button background

I cannot seem to change the background image of my image button. 我似乎无法更改图像按钮的背景图像。 Heres the code i'm currently trying to use: 这是我当前尝试使用的代码:

ImageButton imgButton = (ImageButton) findViewById(R.id.showSportsButton);
imgButton.setBackgroundResource(R.drawable.tab2_selected);

However this seem to be placing the new image on top of the old image leaving me with 2 images overlapping each other. 但是,这似乎是将新图像放置在旧图像的顶部,使我有2张图像彼此重叠。

Does anyone know why this is?? 有人知道为什么吗??

为了解决这个问题,您应该实施

imgButton.setImageResource(R.drawable. tab2_selected);

使用此方法:

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

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

Make sure you are on same activity. 确保您正在进行相同的活动。 If you are changing background of different activity first create the constructor then use object to change button. 如果要更改不同活动的背景,请先创建构造函数,然后使用object来更改按钮。

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

and also check that oncreate() method has void return type if you are using only findviewbyid . 如果仅使用findviewbyid ,还请检查oncreate()方法是否具有void返回类型。

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

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