正如我所知,在用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);
感谢
1) 有什么方法可以在XML中定义onTouch吗?如果有,那么如何使用???
否,android没有提供默认属性,可以在xml
文件中定义触摸事件,您必须在.java文件中编写方法。
2) 或者在onClick监听器内部实现onTouch监听器的任何其他方式;
否,您无法在onClick()
中实现onTouch()
,因为当您第一次触摸或说点击或点击屏幕时会调用onClick事件,并在释放触摸时执行该事件。但它无法检测您的触摸移动,即ACTION_DOWN
、ACTION_UP
等。
所以,如果您想实现onTouch()
事件,您必须自己编写它。
您可以编写一些机制,使您可以轻松地实现onTouch()
事件。但与其这样做,我建议您使用Butterknife库,只需定义annotation
就可以轻松地编写onTouch()
方法。以下是他们如何在注释中绑定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;
}
}
据我所知,您不能将代码直接放入XML中。如果我错了,请纠正我。Activitys类中必须有代码。