AI智能
改变未来

android mvvm databinding在activity中的使用

在自己写的几个项目中,mvvm相比其他(mvc,mvp)框架,个人觉得对于前期编码,以及后期的迭代开发,维护都是比较方便的。将原本繁琐的逻辑处理功能交给了viewmodel层来实现,通过model层可以使用databinding实现页面数据的绑定,findviewById一去不复返了,而且对于点击onclick事件,onCheckedchange等事件不用去实现相关listener相关接口,直接通过布局绑定实现。

MainViewModel

public class MainViewModel {private ActivityMainBinding activityMainBinding;private BaseActivity baseActivity;private String[] authType={\"密码\",\"人脸\"};public MainViewModel(ActivityMainBinding activityMainBinding, BaseActivity baseActivity) {this.activityMainBinding = activityMainBinding;this.baseActivity = baseActivity;activityMainBinding.setMainViewModel(this);activityMainBinding.tvCurrentuser.setText(AppManager.getInstance().getUserModel().userName);}public void onDestroy() {}public void finish(View view){baseActivity.finish();}public void intentUserManage(View view){// chooseCheckType(4);Intent intent=new Intent(baseActivity, UserManageActivity.class);baseActivity.startActivity(intent);}public void intentRecord(View view){Intent intent=new Intent(baseActivity, RecordActivity.class);baseActivity.startActivity(intent);}public void intentDeviceManage(View view){Intent intent=new Intent(baseActivity, DeviceManageActivity.class);baseActivity.startActivity(intent);}public void intentSetting(View view){Intent intent=new Intent(baseActivity, SettingActivity.class);baseActivity.startActivity(intent);}public void intentAllAuth(View view){Intent intent=new Intent(baseActivity, AllAuthActivity.class);baseActivity.startActivity(intent);}public void intentPartAuth(View view){Intent intent=new Intent(baseActivity, PartAuthActivity.class);baseActivity.startActivity(intent);}private void chooseCheckType(int flag){AlertDialog.Builder builder=new AlertDialog.Builder(baseActivity);builder.setTitle(\"选择验证方式\").setItems(authType, new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {switch (which){case 0:Intent intent=new Intent(baseActivity, LoginByPwdActivity.class);intent.putExtra(\"flag\",flag);baseActivity.startActivity(intent);break;case 1:Intent intent1=new Intent(baseActivity, VerifyActivity.class);intent1.putExtra(\"flag\",flag);baseActivity.startActivity(intent1);break;}}});builder.show();}public void receiveEvent() {}}

MainActivity

public class MainActivity extends BaseActivity {private ActivityMainBinding activityMainBinding;private MainViewModel mainViewModel;@Overrideprotected void onCreate( Bundle savedInstanceState) {super.onCreate(savedInstanceState);activityMainBinding= DataBindingUtil.setContentView(this, R.layout.activity_main);mainViewModel=new MainViewModel(activityMainBinding,this);}@Overrideprotected void onDestroy() {super.onDestroy();mainViewModel.onDestroy();}@Overrideprotected void receiveEvent(MessageEvent event) {super.receiveEvent(event);mainViewModel.receiveEvent();}}
赞(0) 打赏
未经允许不得转载:爱站程序员基地 » android mvvm databinding在activity中的使用