I have an ImageView for which I wanted to implement the onClickListener. But when I click on the image, nothing happens. Event the Logcat does not show any errors.
F
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();
}
Most possible cause of such issues can be some invisible view is on the top of view being clicked, which prevents the click event to trigger. So recheck your xml layout properly before searching anything vigorously online.
PS :- In my case, a recyclerView was totally covering the layout and hence clicking on imageView was restricted.
Same Silly thing happed with me.
I just copied one activity and pasted. Defined in Manifest.
Open from MainActivity.java but I was forgot that Copied Activity is getting some params in bundle and If I don't pass any params, just finished.
So My Activity is getting started but finished at same moment.
I had written Toast and found this silly mistake. :P
Well my solution was another one, or let's say, the bug was:
I simply had another imageview with the same id in another <included />
twice-encapsuled xml layout, which was found before the one that i wanted to react on the click. Solution: Give one of them another id...
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();
}
});
I defined an OnClickListener for ImageView as an OnClickListener for a button and it seems to be working fine. Here's what I had. Please try and let us know if it doesn't work.
final ImageView imageview1 = (ImageView) findViewById(R.id.imageView1);
imageview1.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View v) {
try {
Log.i("MyTag","Image button is pressed, visible in LogCat");;
} catch (Exception e) {
Log.e(TAG, e.toString());
}
}
});