I have an Android app, and in the xml layout file I have something like this:
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/checkBoxDone"
android:checked="false"
android:clickable="true"
android:onClick="doneCheckBoxClicked" />
Then in the java code I implemented
public void doneCheckBoxClicked(View v) { ...}
Can I use similar approach for focus changing actions. Have in the xml something like
android:onFocusChanged="editTextFieldFocusChanged"
and then in java code:
public void editTextFieldFocusChanged(View v, boolean hasFocus) { ...}
Or there is no way to do onFocusChange in the xml?
If you are using Android data binding to bind your handlers then you could write a custom BindingAdapter anywhere in your code to pass your handler from xml to java:
@BindingAdapter("app:onFocusChange")
public static void onFocusChange(EditText text, final View.OnFocusChangeListener listener) {
text.setOnFocusChangeListener(listener);
}
And in Handler.java write a getter that returns an anonymous class:
public class Handler {
public View.OnFocusChangeListener getOnFocusChangeListener() {
return new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean isFocussed) {
System.out.print("S");
}
};
}
}
Now in your xml you can pass in the handler like this:
<layout xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
<variable name="handler" type="Handler" />
</data>
<EditText app:onFocusChange="@{handler.OnFocusChangeListener}"/>
</layout>
We can't set focus change listener of editext in xml file like onclick listener. We need to do it in Java file only.
edit_Text.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
Toast.makeText(getApplicationContext(), "got the focus", Toast.LENGTH_LONG).show();
}else {
Toast.makeText(getApplicationContext(), "lost the focus", Toast.LENGTH_LONG).show();
}
}
});
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