Android image change button background

I cannot change the background image of my image button. Here is the code I'm trying to use now:

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

However, this is similar to placing a new image on top of the old image, leaving me with two images overlapping with each other.

Does anyone know why this is?

+4
source share
4 answers

To resolve this issue you must implement

 imgButton.setImageResource(R.drawable. tab2_selected); 
+10
source

Use this method:

 imgButon.setBackground(getActivity().getDrawable(R.drawable.your_icon)); 
+1
source

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

0
source

Make sure you work with the same thing. If you change the background with another activity, first create a constructor, then use the "Change Object" button.

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

and also verify that the oncreate() method has a void return type if you only use findviewbyid .

0
source

Source: https://habr.com/ru/post/1500499/


All Articles