Android ImageView's onClickListener does not work
can you Try this and tell me what happens ?? :
JAVA :
ImageView imgFavorite = (ImageView) findViewById(R.id.favorite_icon);
imgFavorite.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(YourActivityName.this,
"The favorite list would appear on clicking this icon",
Toast.LENGTH_LONG).show();
}
});
or you should add this :
imgFavorite.setClickable(true);
KOTLIN :
imgFavorite.setOnClickListener { view ->
Toast.makeText(this@YourActivityName, R.string.toast_favorite_list_would_appear, Toast.LENGTH_LONG).show()
}
// either you make your imageView clickable programmatically
imgFavorite.clickable = true
// or via xml on your layout file
<ImageView .... android:clickable="true" />
Ok,
I managed to solve this tricky issue. The thing was like I was using FrameLayout
. Don't know why but it came to my mind that may be the icon would be getting hidden behind some other view.
I tried putting the icon at the end of my layout and now I am able to see the Toast
as well as the Log
.
Thank you everybody for taking time to solve the issue.. Was surely tricky..
Actually I just used imgView.bringToFront();
and it helped.
Try by passing the context instead of the application context (You can also add a log statement to check if the onClick
method is ever run) :
imgFavorite.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Log.d("== My activity ===","OnClick is called");
Toast.makeText(v.getContext(), // <- Line changed
"The favorite list would appear on clicking this icon",
Toast.LENGTH_LONG).show();
}
});
Add android:onClick="clickEvent" to your image view.
<ImageView android:id="@+id/favorite_icon"
android:src="@drawable/small_star"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top|right" android:paddingTop="63sp"
android:paddingRight="2sp"
android:onClick="clickEvent" />
In your activity you can create a method with the same name (clickEvent(View v)), and that's it! You can see the log and the toast text too.
public void clickEvent(View v)
{
Log.i(SystemSettings.APP_TAG + " : " + HomeActivity.class.getName(), "Entered onClick method");
Toast.makeText(v.getContext(),
"The favorite list would appear on clicking this icon",
Toast.LENGTH_LONG).show();
}