当前位置:网站首页>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<>();
}
边栏推荐
- 北京程序员的真实一天!!!!!
- The development of mobile IM based on TCP still needs to keep the heartbeat alive
- Pyqt5 displays file names and pictures
- Clickpaas low code platform
- On the day 25K joined Tencent, I cried
- 企业级:Spire.Office for .NET:Platinum|7.7.x
- Rome chain analysis
- Possible stack order of stack order with length n
- 【FineBI】使用FineBI制作自定义地图过程
- Special Edition: spreadjs v15.1 vs spreadjs v15.0
猜你喜欢
Online sql to excel (xls/xlsx) tool
Threejs realizes sky box, panoramic scene, ground grass
Scheduling system of kubernetes cluster
A real day for Beijing programmers!!!!!
What is test development? Why do so many companies hire test developers now?
Threejs realizes the drawing of the earth, geographical location annotation, longitude and latitude conversion of world coordinates threejs coordinates
UI自動化測試從此告別手動下載瀏覽器驅動
Interview related high-frequency algorithm test site 3
An elegant program for Euclid‘s algorithm
Soul 3: what is interface testing, how to play interface testing, and how to play interface automation testing?
随机推荐
BDF application - topology sequence
Deep learning - LSTM Foundation
Number of possible stack order types of stack order with length n
[array]566 Reshape the matrix - simple
Clickhouse synchronization MySQL (based on materialization engine)
测试开发是什么?为什么现在那么多公司都要招聘测试开发?
Scheduling system of kubernetes cluster
[PHP features - variable coverage] improper use, improper configuration and code logic vulnerability of the function
Online sql to excel (xls/xlsx) tool
Ctfshow web entry code audit
Get to know MySQL connection query for the first time
10种寻址方式之间的区别
How to solve the problem that easycvr changes the recording storage path and does not generate recording files?
Enterprise level: spire Office for . NET:Platinum|7.7. x
Interview related high-frequency algorithm test site 3
DFS and BFS concepts of trees and graphs
Threejs rendering obj+mtl model source code, 3D factory model
ClickPaaS低代码平台
25K 入职腾讯的那天,我特么哭了
阿里云ECS使用cloudfs4oss挂载OSS