jjzjj

Android onfocuschange in xml

coder 2023-11-29 原文

我有一个 Android 应用程序,在 xml 布局文件中我有这样的内容:

    <CheckBox
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/checkBoxDone"
    android:checked="false"
    android:clickable="true"
    android:onClick="doneCheckBoxClicked" />

然后在我实现的java代码中

    public void doneCheckBoxClicked(View v) { ...}

我可以使用类似的方法来改变焦点吗?在 xml 中有类似的东西

android:onFocusChanged="editTextFieldFocusChanged"

然后在java代码中:

public void editTextFieldFocusChanged(View v, boolean hasFocus) { ...}

或者xml中没有办法做onFocusChange?

最佳答案

如果您使用 Android 数据绑定(bind)来绑定(bind)您的处理程序,那么您可以在代码中的任何位置编写自定义 BindingAdapter 以将您的处理程序从 xml 传递到 java:

@BindingAdapter("app:onFocusChange")
public static void onFocusChange(EditText text, final View.OnFocusChangeListener listener) {
    text.setOnFocusChangeListener(listener);
}

然后在 Handler.java 中编写一个返回匿名类的 getter:

public class Handler {
    public View.OnFocusChangeListener getOnFocusChangeListener() {
        return new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean isFocussed) {
                System.out.print("S");
            }
        };
    }
}

现在在您的 xml 中,您可以像这样传入处理程序:

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

关于Android onfocuschange in xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37788230/

有关Android onfocuschange in xml的更多相关文章

随机推荐