As i know we can define onClick tag in xml after writing in xml we can use in java code easily by name that specify in xml eg
<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) Is any way to define onTouch
in XML if yes then how to use ???
2) Or any other way to implement onTouch
Listener inside onClick
listener;
here my goal is to interact more than 100 buttons without defining Buttons name as mention below: and also have onTouch
functionality...
Button mbutton;
mbutton = (Button)findViewbyId(R.id.button);
Thanks
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With