android change image button background

2019-02-17 23:59发布

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.

Does anyone know why this is??

4条回答
兄弟一词,经得起流年.
2楼-- · 2019-02-18 00:17

Use this method:

imgButon.setBackground(getActivity().getDrawable(R.drawable.your_icon));
查看更多
萌系小妹纸
3楼-- · 2019-02-18 00:22

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.

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.

查看更多
疯言疯语
4楼-- · 2019-02-18 00:28

in xml file, <Button> write: android:backgroud="@drawable/your_file"

查看更多
干净又极端
5楼-- · 2019-02-18 00:35

For solving this question you should implement

imgButton.setImageResource(R.drawable. tab2_selected);
查看更多
登录 后发表回答