使用数据绑定时,Android EditText不会更新

时间:2016-07-29 05:39:10

标签: android android-databinding

EditText应包含文本"电子邮件地址"。一旦用户按下EditText字段,就应该清除它,以便用户可以填写他的真实电子邮件地址。

使用" Build"," Rebuild project"进行更改。确保正确重新加载数据绑定。

MainActivity

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    final LoginActivityBinding binding = DataBindingUtil.setContentView(this, R.layout.login_activity);
    binding.userEmail.setText("E-mail address");

    binding.setViewmodel(new LoginViewModel(new LoginDataListener() {

        @Override
        public void onLoginClicked() {
            String userEmail = binding.userEmail.getText().toString();
            User user = new User(userEmail, "");
        }
    }));
}

LoginViewModel

public class LoginViewModel {

    private LoginDataListener mDataListener;

    public LoginViewModel(@NonNull final LoginDataListener loginDataListener) {
        mDataListener = loginDataListener;
    }

    public void onLoginClicked(View view){
        mDataListener.onLoginClicked();
    }

    public void onEmailAddressClicked(View view) {
        EditText userEmail = (EditText) view.findViewById(R.id.user_email);
        userEmail.setText("");
    }

login_activity.xml

<EditText
    android:id="@+id/user_email"
    android:onClick="@{viewmodel::onEmailAddressClicked}"
    android:text="@={user.email}"
    android:inputType="textEmailAddress"
    android:layout_gravity="center_horizontal" />

<Button
    android:id="@+id/login_button"
    android:onClick="@{viewmodel::onLoginClicked}"
    android:text="@string/login"
    android:layout_gravity="center_horizontal" />

用户

public class User {

    private String email;

    public User(String email) {
        this.email = email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getEmail() {
        return email;
    }    
}

1 个答案:

答案 0 :(得分:1)

你在这里做错了:

import vlc

执行:

binding.userEmail.setText("E-mail address");

但是为什么你没有将text hint设置为Edittext以达到你的要求呢?