How To Change The Image On Click Of Imagebutton?
Solution 1:
That's why you are using a selector for your button background and the image changes depending on the state of the button. If it is pressed the image will be "on" and in its normal state (no pressed and no focused) the image will be "off".
EDIT:
publicclassMainActivityextendsAppCompatActivity {
ImageButton btn;
boolean isPressed;
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (ImageButton) findViewById(R.id.btn);
btn.setBackgroundResource(R.drawable.normal);
btn.setOnClickListener(newView.OnClickListener() {
@OverridepublicvoidonClick(View v) {
if(isPressed){
v.setBackgroundResource(R.drawable.normal);
}else{
v.setBackgroundResource(R.drawable.pressed);
}
isPressed = !isPressed; // reverse
}
});
}
<ImageButtonandroid:id="@+id/btn"android:text="@string/hello_world"android:layout_width="wrap_content"android:layout_height="wrap_content"/>
Solution 2:
Actually it change the background image but only for few seconds .why ?
I think it's obvious,those items in drawable are for states that ImageButton is pressed by user or in normal mode.
can I write on java side ? can I write on click listener of image button ?
Yes, and yes again :D if you want to change it when user presses it, just do it like this :
XML layout:
<ImageButton android:id="@+id/favorite"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:src="@drawable/off"
android:background="#00ffffff"
/>
Java side (eg. in you onCreate method)
ImageButton favorite;
boolean isFav = false;
publicvoidonCreate(Bundle savedInstanceState){
///...
favorite = findViewById(R.id.favorite);
favorite.setOnClickListener(newView.OnClickListener() {
@OverridepublicvoidonClick(View view) {
isFav = !isFav;
if (isFav){
favorite.setImageResource(R.drawable.on);
}
else{
favorite.setImageResource(R.drawable.off);
}
}
});
///...
}
Solution 3:
change the source of the image by providing an absolute path or an internet url dynamically in the onClickListener of the image.
image.setOnClickListener(newView.OnClickListener() {
@OverridepublicvoidonClick(View view) {
//Here before changing the image you can check if the appropriate //image is set to the view.
image.setImageResource(R.drawable.on);
}
});
and also can be like this
btn.setOnClickListener(newView.OnClickListener() {
@OverridepublicvoidonClick(View v) {
if(isPressed){
v.setBackgroundResource(R.drawable.normal);
}else{
v.setBackgroundResource(R.drawable.pressed);
}
isPressed = !isPressed; // reverse
}
});
Post a Comment for "How To Change The Image On Click Of Imagebutton?"