TextWatcher的数据绑定在Android上不起作用

问题描述 投票:1回答:1

我正在创建密码创建屏幕,我想在输入密码时显示密码强度指示符。我的布局如下所示:

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <data>
        <variable
            name="viewModel"
            type="com.example.PasswordViewModel" />
    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:textChangedListener="@{viewModel.passwordTextWatcher}" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="@{viewModel.passwordQuality}"/>

    </LinearLayout>

</layout>

PasswordViewModel.java如下所示

public class PasswordViewModel extends BaseObservable {

    private String password;

    @Bindable
    public String getPasswordQuality() {
        if (password == null || password.isEmpty()) {
            return "Enter a password";
        } else if (password.equals("password")) {
            return "Very bad";
        } else if (password.length() < 6) {
            return "Short";
        } else {
            return "Okay";
        }
    }

    public void setPassword(String password) {
        this.password = password;
        notifyPropertyChanged(BR.passwordQuality);
    }



@Bindable
public TextWatcher getPasswordTextWatcher() {
    return new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            // Do nothing.
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            setPassword(s.toString());
        }

        @Override
        public void afterTextChanged(Editable s) {
            // Do nothing.
        }
    };
}

最后]

public class EditTextBindingAdapters {

    @BindingAdapter("textChangedListener")
    public static void bindTextWatcher(EditText editText, TextWatcher textWatcher) {
        editText.addTextChangedWatcher(textWatcher);
    }
}

但是当我开始写onTextChanged方法时没有调用!谁能帮我解决这个问题?谢谢,提前。

我正在创建密码创建屏幕,我想在输入密码时显示密码强度指示符。我的布局如下所示:

android data-binding android-databinding
1个回答
1
投票

根据对问题的描述,您似乎没有在活动中初始化绑定。如果是这种情况,则

© www.soinside.com 2019 - 2024. All rights reserved.