Reputation: 35
I have imageview and i whant when user click this imageview the background of this changed this is my code
btnImage =(ImageView) findViewById(R.id.image_button);
btnImage.setOnClickListener(new OnClickListener(){
public void onClick(View arg0) {
Intent i=new Intent(fierst.this,second.class);
startActivity(i);
}
});
but i dont know how in onclick change this background image
Upvotes: 0
Views: 4395
Reputation: 26
I'm agree with @sajidkhan answer but @zahra you are doing mistake to set the selector as background wrong. here i will explain @sajidkhan's answer as i know he might be expected here an image.png etc not a selector.xml
buttonONE.setBackground(R.drawable.round_button_focus);
round_button_focus means round_button_focus.png etc,
in MotionEvent.ACTION_DOWN
set one background and when you release the button set another background eg. MotionEvent.ACTION_UP
follow @sajidkhan suggestion his answer might deserve as accepted if you think this helped you.
Upvotes: 1
Reputation: 618
Why you do not use Selctor for ImageView
when clicked.
res/drawable/selector.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/your_iamge_pressed" android:state_pressed="true" />
<item android:drawable="@drawable/your_iamge_pressed"
android:state_focused="true"
android:state_enabled="true"
android:state_window_focused="true" />
<item android:drawable="@drawable/your_iamge_normal" />
here in you ImageView set the selector as background : android:background="@drawable/selector.xml"
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/selector.xml" />
OR USE TouchListener To implement such idea when you touch(Action Down) set one image as background and when you release (Action Up) set another Image as background.
here is the code
buttonONE.setOnTouchListener(new View.OnTouchListener(){
@Override
public boolean onTouch(View v, MotionEvent event)
{
if(event.getAction() == MotionEvent.ACTION_DOWN) {
buttonONE.setBackground(R.drawable.round_button_focus);
} else if (event.getAction() == MotionEvent.ACTION_UP) {
buttonONE.setBackground(R.drawable.round_button_unfocused);
// *******start Intent here********
}
}
};
Upvotes: 3
Reputation: 1238
Here is the code
btnImage =(ImageView) findViewById(R.id.image_button);
btnImage.setOnClickListener(new OnClickListener(){
public void onClick(View arg0) {
btnImage.setBackgroundResource(R.drawable.ic_launcher);
//put your image in drawable folder and change ic_luncher by your image.
Intent i=new Intent(fierst.this,second.class);
startActivity(i);
}
});
Intent i=new Intent(fierst.this,second.class);
startActivity(i);
by executing these two line it will move to second activity so you can't able to see the result for image changed or not. To see the proper output for image change make these lines as comment
Hope this will helpful .thanks
Upvotes: 0