Android将BindingAdapter用于EditText

时间:2019-03-21 18:30:21

标签: android android-databinding

在我的应用程序的简单部分中,我想使用BindingAdapter自定义编辑文本为

  1. 检测edittext为空
  2. 检测edittext是否具有默认值

在我的代码中,我可以使用简单的数据绑定方式,但是它不能用BindingAdapter来实现,因为我可以做到这一点,并且存在很大的问题,那就是我的代码无法检测到editText默认值以及何时我得到编辑文本值,我得到空值

在活动中附加默认值:

binding.instagramPageName.setText("1234");
binding.instagramPagePassword.setText("123456");

ViewModel:

public class LoginViewModel extends ViewModel {
    private InstagramAccount instagramAccount;
    private LoginResultCallback loginResultCallback;
    public ObservableField<String> text = new ObservableField<>();

    public LoginViewModel(LoginResultCallback callback) {
        instagramAccount = new InstagramAccount();
        loginResultCallback = callback;
    }

    public TextWatcher getUserAccountPageName() {
        return new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                instagramAccount.setUserPage(s.toString());
            }
        };
    }

    public TextWatcher getUserPagePassword() {
        return new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                instagramAccount.setUserPassword(s.toString());
            }
        };
    }

    public void onLoginClicked(View view) {
        if (instagramAccount.isValidate()) {
            loginResultCallback.onSuccessValidation();
            getResult();
        } else {
            loginResultCallback.onErrorValidation();
        }
    }
}

然后是我的布局

<EditText
    android:id="@+id/instagram_page_name"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:addTextChangedListener="@{viewModel.getUserAccountPageName}"
/>

0 个答案:

没有答案