Reputation: 35
I have a star image in my activity. Now when the user clicks on that star image, that image should change to ON Star image, Same as favorite star image. For this I use the following code :
ImageView star=(ImageView)findViewById(R.id.favorite);
star.setOnTouchListener(new OnTouchListener()
{
@Override
public boolean onTouch(View v, MotionEvent event)
{
if(event.getAction()==MotionEvent.ACTION_DOWN)
{
star.setImageResource(android.R.drawable.star_big_on);
}
return false;
}
});
But I am unable to change that image. Please suggest me.
Upvotes: 0
Views: 136
Reputation: 49
you can use selctor xml. create xml under res/drawable and then create selector_star.xml, your code in that xml should like this :
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/star_big_on" android:state_pressed="true" android:state_selected="true"></item>
<item android:drawable="@drawable/star_big_off"></item>
</selector>
and in your Image view xml, it should like this :
<ImageView
android:id="@+id/star"
android:background="@drawable/star_selector"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
Upvotes: 0
Reputation: 446
To change the image you can use this code :
star.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
star.setImageResource(android.R.drawable.star_big_on);
}
});
Upvotes: 0
Reputation: 2290
Use an OnClickListener instead of an OnTouchListener.
ImageView star=(ImageView)findViewById(R.id.favorite);
star.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
star.setImageResource(android.R.drawable.star_big_on);
}
});
Your code should look like that. You'll need to make the ImageView clickable as well either in XML (android:clickable="true") or in code (star.setClickable(true);).
Conversely, you could use an ImageButton and set the image as the ImageButton's background. This way you don't have to worry about setting the View to be clickable, as it is inherently clickable.
Upvotes: 1