Model-View-ViewMode架构,可看作MVP改进版,将此前Presenter的逻辑操作交给ViewMode中的Binder去处理
在build.gradle中android节点添加如下代码(最低SDK版本为API7,Gradle版本为1.5.0-alpha1)
dataBinding{
enabled = true
}
创建数据实体类LoginInfo
public class LoginInfo extends BaseObservable {
private String mUser;
private String mPassword;
public LoginInfo(String user, String password) {
mUser = user;
mPassword = password;
}
@Bindable
public String getUser() {
return mUser;
}
public void setUser(String user) {
mUser = user;
notifyPropertyChanged(BR.user);
}
@Bindable
public String getPassword() {
return mPassword;
}
public void setPassword(String password) {
mPassword = password;
notifyPropertyChanged(BR.password);
}
}
LoginModel封装维护LoginInfo、点击事件、文本改变事件
public class LoginModel {
private static final String DEF_USER = "song";
private static final String DEF_PASSWORD = "123";
public LoginInfo mInfo;
private OnLoginListener mListener;
public LoginModel(OnLoginListener listener) {
mListener = listener;
mInfo = new LoginInfo("", "");
}
public TextWatcher getUserTextWatcher() {
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) {
mInfo.setUser(s.toString());
}
};
}
public TextWatcher getPasswordTextWatcher() {
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) {
mInfo.setPassword(s.toString());
}
};
}
public interface OnLoginListener {
void onLoginSuccess();
void onLoginFail();
}
public void onLoginClick(View view) {
if (mInfo.getUser().equals(DEF_USER) && mInfo.getPassword().equals(DEF_PASSWORD)) {
mListener.onLoginSuccess();
} else {
mListener.onLoginFail();
}
}
}
xml文件根节点变为layout,布局分为
MainActivity开启线程3秒后修改数据会显示在UI
public class MainActivity extends AppCompatActivity implements LoginModel.OnLoginListener {
private static final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
LoginModel model = new LoginModel(this);
binding.setModel(model);
new Thread(new Runnable() {
@Override
public void run() {
SystemClock.sleep(3000);
model.mInfo.setUser("New User");
model.mInfo.setPassword("New Password");
}
}).start();
}
@Override
public void onLoginSuccess() {
Log.d(TAG, "onLoginSuccess: ");
}
@Override
public void onLoginFail() {
Log.d(TAG, "onLoginFail: ");
}
}