Android:基于 jetpack 组件的 mvvm 模式(架构)

这边直接给个超级简单案例吧,刚刚实现出来,开心的一批

Android:基于 jetpack 组件的 mvvm 模式(架构)_第1张图片

如图

代码,我就直接粘贴了

activity_login.xml



    
        
    

    
        
        

 LoginViewModel.java


public class LoginViewModel extends AndroidViewModel {


    private static ActivityLoginBinding binding;
    @SuppressLint("StaticFieldLeak")
    private static LoginActivity loginActivity;


    public static MutableLiveData _btn=new MutableLiveData<>();
    //liveData
    private MutableLiveData _str;
    public LoginViewModel(@NonNull Application application) {
        super(application);

        _btn.setValue("认 证");
        //_str.setValue("");
    }

    public void setBinding(ActivityLoginBinding binding, LoginActivity loginActivity) {
        //把binding和mainActivity都赋值给MainVM作为静态变量备用,因为很多绑定的控件都只能用静态方法
        LoginViewModel.binding =binding;
        LoginViewModel.loginActivity =loginActivity;
    }
    //值得学习的一篇文章
    //https://blog.csdn.net/qq_25890433/article/details/116310790?utm_medium=distribute.pc_relevant.none-task-blog-2~default~baidujs_baidulandingword~default-1.no_search_link&spm=1001.2101.3001.4242.2
//这个是给activity双向通信用的
    public MutableLiveData get_str(){
        if (_str ==null){
            _str = new MutableLiveData<>();
            _str.setValue("");
        }
        return _str;
    }

    public void certification(){
        String phone = _str.getValue();
        Log.e("phone",phone);
        if (phone.equals("1836xxx2900")){
            Intent intent = new Intent(loginActivity,ListActivity.class);
            loginActivity.startActivity(intent);
        }
    }
}

 LoginActivity.java

public class LoginActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //顶部框颜色
        SystemUtil.setStatusBarColor(this, Color.parseColor("#20B2AA"));
        //绑定工作
        ActivityLoginBinding binding = DataBindingUtil.setContentView(this,R.layout.activity_login);
        LoginViewModel loginViewModel = new ViewModelProvider(this,new ViewModelProvider.AndroidViewModelFactory(getApplication())).get(LoginViewModel.class);
        //绑定工作
        binding.setLoginvm(loginViewModel);
        //建立感应
        binding.setLifecycleOwner(this);
        //把他当作初始化函数使用更方便,比如要用个列表
        loginViewModel.setBinding(binding,this);
    }
}

记录一下,遇到一个问题

测试下来发现,viewmodel好像不能充填listview,这个让我有点难搞,是不是还得拿给adtivity去充填listview

——————————————————————————

若是EditText,则将 @{vm.text} 改成 @={vm.text}就可以实现修改编辑框,在vm中的text.getValue()时可以实施获取数据,即数据双向绑定。

viewModel->管理ui的数据

        感应改变数据->liveData + ui刷新/管理整个布局 - >DataBinding

有一个要注意的点是,xxViewModel,的首字母一定要大写,否则会报如下的错误

Cause: couldn't make a guess for xxxxx viewmodel

注释:

DataBinding需要在build.gradle的android下面加入

    buildFeatures{
        dataBinding = true // for data binding
        viewBinding = true // for view binding
    }
dataBinding{
   enabled true
}

//或者可以这么写
//dataBinding.enable=true

交给DataBinding管理所有布局, 添加如下代码后,就可以不再使用findviewbyid,setonclicklistener,都不需要写




       




或者可以这么写


        

        



            ..所有布局..

布局的控件可以这么写

android:text="@{vm.xxxx}"

,xxxx是在viewmodel当中定义的方法

magnetActivity.java案例
public class magnetActivity extends AppCompatActivity {
    private ActivityMagnetBinding binding;
    private MagnetViewModel magnetviewmodel;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //顶部框颜色
        SystemUtil.setStatusBarColor(this, this.getResources().getColor(R.color.top_background_color));
        SystemUtil.setAndroidNativeLightStatusBar(this,true);
        //绑定工作
        binding = DataBindingUtil.setContentView(this,R.layout.activity_magnet);
        magnetviewmodel = new ViewModelProvider(this,new ViewModelProvider.AndroidViewModelFactory(getApplication())).get(MagnetViewModel.class);
        //绑定工作
        binding.setMagnetvm(magnetviewmodel);
        //建立感应
        binding.setLifecycleOwner(this);
    }
}

 MagnetViewModel.java案例


public class MagnetViewModel extends /*ViewModel*/ AndroidViewModel {

    //ui data

    //liveData
    private MutableLiveData  _search;


    private Context context;

    private magnetList_C magnetList_c;
    private List magnetList_cList = new ArrayList();
    private magnetList_A magnetList_a;
    private String btsowUrl = "https://btsow.com/search/";

    public MagnetViewModel(@NonNull Application application) {
        super(application);
        context = application;
    }

    public MutableLiveData get_search(){
        if (_search ==null){
            _search = new MutableLiveData<>();
            _search.setValue("");
        }
        return _search;
    }

    //清空
    public void clearSearch(){
        _search.setValue("");
    }
    //开始搜索
    public void startSearch(){
        okhttp_text(_search.getValue());
    }
    //拿到检索的数据
    private void okhttp_text(String search) {
        magnetList_cList.clear();
        //创建okHttpclient的对象
        OkHttpClient okHttpClient = new OkHttpClient();
        //创建Request,Builder
        Request.Builder builder = new Request.Builder();
        //使用Request.Builder对象,调用Url方法,传入网路路径
        Request.Builder url = builder.url(btsowUrl+search);
        //使用Request.Builder对象,调用builder方法构件request对象
        Request request = url.build();
        //创建一个Call对象,参数就request对象
        Call call = okHttpClient.newCall(request);
        //使用call对象,调用enqueue方法,请求加入调度(异步加载)

        call.enqueue(new Callback() {
            //当请求失败的时候,调用此方法
            @Override
            public void onFailure(Call call, IOException e) {
                //andler.sendEmptyMessage(FALL);
            }

            //当请求成功的时候,调用此方法
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String source = response.body().string();
                System.out.print(source);
                //此处拿到数据,要传递给adtivity去更新
            }
        });
    }
}





    
        
    

。。。。。略

你可能感兴趣的:(android,java,android,java,apache)