I just added a new drawable
folder under res
folder. In the drawable
folder, i copied the ic_launcher.png
file from
This misled me a bit - it should be setImageResource
instead of setBackgroundResource
:) !!
The following works fine :
ImageButton btn = (ImageButton)findViewById(R.id.imageButton1);
btn.setImageResource(R.drawable.actions_record);
while when using the setBackgroundResource
the actual imagebutton's image
stays while the background image is changed which leads to a ugly looking imageButton object
Thanks.
You can do it right in your XML file:
android:onClick="@drawable/ic_action_search"
<ImageButton android:src="@drawable/image_btn_src" ... />
image_btn_src.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@drawable/icon_pressed"/>
<item android:state_pressed="false" android:drawable="@drawable/icon_unpressed"/>
</selector>
You have assing button to your imgButton
variable:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgButton = (Button) findViewById(R.id.imgButton);
imgButton.setOnClickListener(imgButtonHandler);
}
It is very simple
public void onClick(View v) {
imgButton.setImageResource(R.drawable.ic_launcher);
}
Using set Background image resource will chanage the background of the button
That is because imgButton is null. Try this instead:
findViewById(R.id.imgButton).setBackgroundResource(R.drawable.ic_action_search);
or much easier to read:
imgButton = (Button) findViewById(R.id.imgButton);
imgButton.setOnClickListener(imgButtonHandler);
then in onClick: imgButton.setBackgroundResource(R.drawable.ic_action_search);