0

I create custom view and use it in some xml activity then set android:onClick="buttonOnClick". I defined buttonOnClick as public and write it in its activity and set tools:context.
Activity.java

 public void buttonOnClick(View view) {
        validate(view);
    }

layout.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    ...
    tools:context="com.test.myapp.Activity">

   <com.test.myapp.GifImageViewComp
      ....
    android:onClick="buttonOnClick"  />

it's working on Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP but in other OS version, custom view xml onclick attribute try to find handler from view class instead of activity.

I don't want use implementation of onClick or setOnClickListener on every view, i want use onClick in layout of activity

Mohammad Javad
  • 573
  • 1
  • 7
  • 29

1 Answers1

1

It's just not clear the relationship between a button in your xml and a method in your activity that reacts to the click events unless you explicitly see it defined in your Java file. With the android:onClick approach you can even forget that you have a button in your layout or which is the method that is handling its onClick event.

Source

You should use OnClickListener instead of android:onClick .

Interface definition for a callback to be invoked when a view is clicked.

This method takes the reference to the Listener and registers a callback to be invoked when the View is clicked.

FYI

Make sure you set android:clickable="true" in XML . you should specify this attribute .

<com.test.myapp.GifImageViewComp
    android:clickable="true"
    android:onClick="buttonOnClick"  />
IntelliJ Amiya
  • 74,896
  • 15
  • 165
  • 198