Piyush Yawalkar Piyush Yawalkar - 3 months ago 12
Android Question

Not able to find onclick method assigned to ImageView

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="0dp"
android:paddingRight="0dp"
android:paddingTop="0dp"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MissedCallServices"
>
<android.support.v7.widget.Toolbar
android:id="@+id/my_toolbar"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#ffff00"
android:elevation="4dp"
android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
>
<ImageView
android:layout_width="100dp"
android:layout_height="match_parent"
android:src="@drawable/icon"
/>
<ImageView
android:layout_width="100dp"
android:layout_height="match_parent"
android:src="@drawable/home"
android:baselineAlignBottom="false"
android:layout_gravity="right"
android:onClick="gotoHome"
android:clickable="true"
android:enabled="true"
/>
</android.support.v7.widget.Toolbar>
</RelativeLayout>


Above mentioned is the layout of my activity in 2nd ImageView I have given onClick="gotoHome" but I am getting no such method exception.
I dont know why I am getting such exception and this is running properly in emulator

Answer

Well it is happening because of android:theme attribute of your Toolbar,Your onClick gets the wrong Context (android.support.v7.internal.view.ContextThemeWrapper is not your Activity). Try implementing listeners in code, don't use through xml. Remove theme attribute and use style instead

Lets say imageview has id home

ImageButton homeButton = (ImageButton ) findViewById(R.id.yourbuttonid)
homeButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                 //here comes the code
 Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish();
            }
});