当前位置:网站首页>Learning MVVM notes (1)

Learning MVVM notes (1)

2022-07-05 04:08:00 One Zen - little monk

MVVM

model : The data layer , Contains data entities and operations on data entities
View : Interface layer , Corresponding Activity XML view Responsible for data display and user interaction
ViewModel : Correlation layer take model and view Binding ,model perhaps View When changes , Refresh each other in real time

Be careful :
1.View Only and UI Related work , No business logic involved , There is no operational data involved , Don't process data .UI Strictly separate from the data
2.ViewModel Only do work related to business logic , It doesn't involve anything and UI Related operations , Does not hold control references , Not updated UI.

DataBinding It is a library officially recommended by Google ,DataBinding Library to write statements layouts file , You can bind your with the least code app Logic and layouts file ,DataBinding It's a support library
(1) Set up the environment
stay app Of build.gradle Add... To the file

android {
     .... dataBinding {
     enabled = true } }

(2) To write layout file
Start tag is layout, Next is data Element one view Elements , This view Element is not used DataBinding Of layout The root element of the file

stay data Describe a name The variable properties of , Make it available in layout Use in ,type For the binding of data object

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
    <data>
        <variable
            name="user"
            type="com.example.mvvmdemo.User" />
    </data>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <TextView
            android:id="@+id/tv_name"
            android:text="@{user.mUserName}"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
        <TextView
            android:id="@+id/tv_age"
            android:text='@{
    user.mUserage + ""}'
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
    </LinearLayout>
</layout>

data object :

package com.example.mvvmdemo;

public class User {
    

    public final String mUserName;
    public final int mUserage;

    public User(String userName, int userAge) {
    
        this.mUserName = userName;
        mUserage = userAge;
    }

}

(3)Binding data
By default , One Binding Class will be based on layout Generated by the name of the file , Convert it to ( Naming conventions for capital letters , And add Binding suffix ) , Aforementioned layout File is activity_main.xml , Therefore, the generated class name is ActivityMainBinding. This class contains from layout Attributes to layout Of views All in bindings( Include user Variable ) , And I also know how to give Binding Expression assignment value , establish bindings The simplest of inflating(layout Document and Activity/Fragment Link to )

public class MainActivity extends AppCompatActivity {
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
        super.onCreate(savedInstanceState);
        ActivityMainBinding binding = DataBindingUtil.setContentView(this,R.layout.activity_main);
        User user = new User("haha" , 22);
        binding.setUser(user);
    }
}

** If in ListView perhaps RecyclerView adapter Use DataBinding when , Will use
**

ListItemBinding binding = ListItemBinding.inflate(layoutInflater, viewGroup, false); //or
ListItemBinding binding = DataBindingUtil.inflate(layoutInflater, R.layout.list_item, viewGroup, false);

The other thing to note is that : If you will User If the variable in the class is changed to private, an error will be reported .

Found data binding errors. ****/ data binding error ****msg:Could not find accessor demo.com.databindingdemo.User.mUserName

(4) Event handling
Data binding allows you to write expressions to handle view Dispatched events , The event attribute name depends on the listener method name .

public class MyHandler {
    
    public void myOnClick(View view){
    
        Toast.makeText(view.getContext(),"hello",Toast.LENGTH_SHORT).show();
    }
    public boolean myOnLongClick(View view){
    
        Toast.makeText(view.getContext(),"hello world",Toast.LENGTH_SHORT).show();
        return true;
    }
}
<layout xmlns:android="http://schemas.android.com/apk/res/android">
    <data>
        <variable name="handlers" type="com.heyy.databingexample.MyHandler"/>
    </data>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text=" Test event binding "
            android:onClick="@{handlers::myOnClick}"
            android:onLongClick="@{handlers::myOnLongClick}"/>
    </LinearLayout>
</layout>

(5) thorough DataBinding usage
import : Zero or more import Elements may be in data Use... In elements , These are only for your layout Add references... To the file

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
    <data>
        <variable
            name="user"
            type="com.example.mvvmdemo.User" />
        <import type="android.view.View"/>
    </data>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <TextView
            android:id="@+id/tv_name"
            android:text="@{user.mUserName}"
            android:visibility="@{user.mUserage == 22 ? View.VISIBLE : View.GONE}"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
        <TextView
            android:id="@+id/tv_age"
            android:text='@{
    user.mUserage + ""}'/>

When class names conflict , have access to alias Rename

<import type="android.view.View"
    alias="test"/>

android:visibility="@{user.mUserage == 22 ? test.VISIBLE : test.GONE}"

Imported types can also be used in expressions static Properties and usage

public class StringUtls {
    
    public static String translateStr(String str){
    
        return str+"haha";
    }
}

<import type="com.example.mvvmdemo.StringUtls"/>

android:text="@{StringUtls.translateStr(user.mUserName)}"

(6)Data object
DataBinging Allows us to create observable objects , Fields and collections , When our data changes , To notify other objects, you can use DataBinding

Observable object
Realization android.databinding.Observable The class of the interface allows you to attach a listener to Bound object , In order to monitor the changes of all attributes on the object .
One BaseObervabke The base class of is created to implement the listener registration mechanism .

public void setmUserName(String mUserName) {
    
    this.mUserName = mUserName;
    notifyPropertyChanged(BR.user);
 }

Observable aggregate
Oberservable Collection allows controls to access these data object ,ObservableArraMap The key used is a reference type , Such as string

ObservableArrayMap<String, Object> user = new ObservableArrayMap<>(); user.put("name", "Jack"); user.put("age", 17);

<data> 
<import type="android.databinding.ObservableMap"/> 
<variable name="user" type="ObservableMap<String, Object>"/> </data> 
<TextView
android:text='@{
    user["name"]}' 
android:layout_width="wrap_content" 
android:layout_height="wrap_content"/> 
<TextView 
android:text='@{
    String.valueOf(1 + (Integer)user["age"])}' 
android:layout_width="wrap_content" 
android:layout_height="wrap_content"/>

Observable Field
ObservableFields It contains Observable object .

<data>
    <variable
        name="itemViewModel"
        type="com.autoai.project.home.viewmodel.AppItemViewModel" />
</data>

 Use 
android:text="@{itemViewModel.appTitle}"
 class 
public class AppItemViewModel {
    
public ObservableField<String> appTitle = new ObservableField<>();
}
原网站

版权声明
本文为[One Zen - little monk]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/186/202207050405459899.html