Search code examples
androidonclickonclicklistenerandroid-custom-viewbuttonclick

How to set android:onClick in xml of a custom view?


I saw this SO question, and want to implement accepted answer for a custom view.

Because in the xml of my custom view, it doesn't recognize any method for android:onClick for any buttons! I wonder if it is because of custom view, maybe I should just use onClick method in xml of an activity.

Is it possible to set a method for a button android:onClick attribute in a user-defined custom view (which extends LinearLayout), like below:

it is my custom view:

public class CustomEditText extends LinearLayout{
...
    public void myMethod(View v) {

        switch (v.getId()) {
        case R.id.btn_down:
            // do stuff;
            break;
        case R.id.btn_down_double:
            // do stuff;
            break;
        }
    }

}

and it is my xml file:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:orientation="horizontal">

    <LinearLayout
        android:layout_height="wrap_content"
        android:layout_weight="wrap_content"
        android:background="@drawable/bg_ctrl"
        android:orientation="vertical">

        <android.support.v7.widget.AppCompatButton
            android:id="@+id/btn_down"
            style="@style/CustomButton"
            android:onClick="myMethod"
            android:theme="@style/CustomButton.RED" />

        <android.support.v7.widget.AppCompatButton
            android:id="@+id/btn_down_double"
            style="@style/CustomButton"
            android:onClick="myMethod"
            android:theme="@style/CustomButton.RED2" />

    </LinearLayout>

</LinearLayout>

it is the error:

FATAL EXCEPTION: main
java.lang.IllegalStateException: Could not find method myMethod(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton with id 'btn_down'

UPDATE:

parent of this custom view is a fragment and I moved myMethod() to that fragment, but the error still insists :-|


Solution

  • This has to be in your activity class code:

        public void myMethod(View v) {
    
            switch (v.getId()) {
              case R.id.btn_down:
                // do stuff;
                break;
              case R.id.btn_down_double:
                // do stuff;
                break;
            }
        }