美文网首页
Android MVVM Demo

Android MVVM Demo

作者: 无敌未央様 | 来源:发表于2019-08-07 09:01 被阅读0次

    我写了一个简单的登录demo,用的是传统的Data Binding来实现Android的MVVM架构。对于MVVM我觉得是对MVP架构中P层的一次升华,进一步的解耦,同时view与model又是双向绑定,这种绑定又是支持生命周期检测,不用担心页面销毁了还有回调出现,不需要findViewById也不需要butterknife,不需要拿到具体的View去设置数据绑定监听器等等,全由data binding帮我们完成。

    build.gradle(app)

    dataBinding{
            enabled=true
     }
    

    布局

    activity_main.xml

    <?xml version="1.0" encoding="utf-8"?>
    <layout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools">
        <data>
            <variable
                name="viewModel"
                type="com.leostadyn.stackfarm.mvvmtest.UserViewModel" />
        </data>
    
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            tools:context=".MainActivity">
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="@={viewModel.user.status}"
                android:id="@+id/txt_user_login_status"/>
            <EditText
                android:id="@+id/edit_username"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="@={viewModel.user.userName}"
                android:hint="username"/>
            <EditText
                android:id="@+id/edit_password"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="@={viewModel.user.password}"
                android:hint="password"/>
            <Button
                android:id="@+id/btn_submit"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textAllCaps="false"
                android:onClick="click"
                android:text="submit"/>
    
            <ProgressBar
                android:id="@+id/progressBar"
                android:visibility="gone"
                style="?android:attr/progressBarStyle"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
    
    
        </LinearLayout>
    </layout>
    

    Model

    User.java

    import android.databinding.ObservableField;
    //User模型
    public class User {
        //用户名
        public ObservableField<String >userName=new ObservableField<>();
        //密码
        public ObservableField<String >password=new ObservableField<>();
        //反馈
        public ObservableField<String >status=new ObservableField<>();
    
        public User() {
        }
    }
    

    ViewModel

    UserViewModel.java

    import android.content.Context;
    import android.util.Log;
    import com.leostadyn.stackfarm.mvvmtest.databinding.ActivityMainBinding;
    public class UserViewModel {
        private Context context;
        private ActivityMainBinding activityMainBinding;
        public static final String TAG="KKKKKKK";
        public User user;
        public UserLocalData data;
        public UserViewModel(Context context, ActivityMainBinding activityMainBinding){
            this.context=context;
            this.activityMainBinding=activityMainBinding;
        }
        public void init(){
            this.user=new User();
            this.activityMainBinding.setViewModel(UserViewModel.this);
            data=new UserLocalData();
        }
        //登录
        public void login(){
            //业务逻辑
            Log.e(TAG,"status:"+user.status.get());
            Log.e(TAG,"username:"+user.userName.get());
            Log.e(TAG,"password:"+user.password.get());
            //权限的校验
            if (data.findByUser(this.user))
                this.user.status.set("success");
            else
                this.user.status.set("error");
        }
    }
    

    View

    MainActivity.java

    public class MainActivity extends AppCompatActivity {
        UserViewModel userViewModel;
        ProgressBar progressBar;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    //        setContentView(R.layout.activity_main);
            ActivityMainBinding dataBindingUtil=DataBindingUtil.setContentView(MainActivity.this,R.layout.activity_main);
            userViewModel=new UserViewModel(MainActivity.this,dataBindingUtil);
            progressBar=findViewById(R.id.progressBar);
        }
        @Override
        protected void onStart() {
            super.onStart();
            userViewModel.init();
        }
        public void click(View view) {
            progressBar.setVisibility(View.VISIBLE);
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    userViewModel.login();
                    progressBar.setVisibility(View.GONE);
                }
            },2000);
        }
    }
    

    模拟数据处理

    public class UserLocalData {
        //模拟数据库
        String [] userArray={"user1:password1","user2:password2"};
        public UserLocalData() {
        }
        //查找用户
        public boolean findByUser(User user){
            if(user==null)
                throw  new NullPointerException("this user object is null");
            for (int i = 0; i <userArray.length; i++) {
                String  userStr=userArray[i];
                String [] userArray=userStr.split(":");
                String username=userArray[0];
                String password=userArray[1];
                if((user.userName.get()).equals(username)&& (user.password.get()).equals(password)){
                    return true;
                }
            }
            return false;
        }
    }
    

    相关文章

      网友评论

          本文标题:Android MVVM Demo

          本文链接:https://www.haomeiwen.com/subject/lxsndctx.html