如何在 XML 中实现 OnTouch 侦听器

How to Implement OnTouch Listener in XML

据我所知,我们可以在 xml 中写入后在 xml 中定义 onClick 标签,我们可以通过在 xml 中指定的名称轻松地在 java 代码中使用,例如

<Button android:id="@+id/mybutton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button"
    android:onClick="myClick" />

public void myClick(View v) {
    // does something very
}

1) 有没有办法在XML中定义onTouch 如果是那么如何使用???

2) 或者任何其他方式在 onClick 监听器中实现 onTouch 监听器;

这里我的目标是在不定义按钮名称的情况下与 100 多个按钮进行交互,如下所述:并且还具有 onTouch 功能...

    Button mbutton;
    mbutton = (Button)findViewbyId(R.id.button);

谢谢

据我所知,您不能将代码直接放入 XML。如果我错了,请纠正我。您必须在活动 Class.

中有代码

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

No,android没有提供默认属性让你在xml文件中定义触摸事件,你必须把方法写在.java 文件.

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

,你不能在onClick()中实现onTouch(),因为当你第一次触摸或说点击或点击屏幕时会调用onClick事件并在您释放触摸时执行事件。但它无法检测到您的触摸动作,即 ACTION_DOWNACTION_UP

所以如果你想实现onTouch()事件,你必须自己写。

您可以编写一些机制,让您轻松实现 onTouch() 事件。但我建议您不要这样做,而是使用 Butterknife library which will let you write onTouch() method easily just by defining annotation. Here's the code 他们如何在注释中绑定 onTouch() (以防您想编写自己的机制)。

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;
    }
}