How to Implement OnTouch Listener in XML

1) Is any way to define onTouch in XML if yes then how to use ???

No, there is no default attribute provided by android that lets you define touch event in xml file, you have to write the method in .java file.

2) Or any other way to implement onTouch Listener inside onClick listener;

No, you cannot implement onTouch() inside onClick() because onClick event gets called when you touch or say click or tap the screen for the first time and performs the event when you release touch. But it is not able to detect the movement of your touch i.e. ACTION_DOWN, ACTION_UP etc.

So if you want to implement onTouch() event, you will have write it on your own.

You can write some mechanism that can let you implement onTouch() event easily. But instead of doing that I'd suggest you to use Butterknife library which will let you write onTouch() method easily just by defining annotation. Here's the code how they have binded onTouch() in annotation (in case you want to write your own mechanism).


Hope this helps some one

You can easily do it using databinding:

step1

public class DataBidingAdapter{

 @SuppressLint("ClickableViewAccessibility")
    @BindingAdapter("touchme")
    public static void setViewOnTouch(TextView view, View.OnTouchListener listener) {
       view.setOnTouchListener(listener);
    }
}

step 2 in xml

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <data>       
        <variable
            name="handlers"
            type="com.user.handlers.Handlers" />

    </data>

    <LinearLayout xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">  
        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="16dp"
          >

            <EditText
                android:id="@+id/search"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/search_for_chats_title"
                app:touchme="@{handlers.searchPatient}" />
        </FrameLayout>
</linearLayout>
</layout>
step 3
 public class Handler{
 public boolean searchPatient(View v, MotionEvent event) {
        if (MotionEvent.ACTION_UP == event.getAction()) {
          //your code
        }
        return true;
    }
}