当前位置:网站首页>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<>();
}
边栏推荐
- Uni app common functions /api
- Kwai, Tiktok, video number, battle content payment
- Containerd series - what is containerd?
- As soon as I write the code, President Wang talks with me about the pattern all day
- 学习MVVM笔记(一)
- Wechat applet development process (with mind map)
- 企业级:Spire.Office for .NET:Platinum|7.7.x
- 面试字节,过关斩将直接干到 3 面,结果找了个架构师来吊打我?
- C language course setting: cinema ticket selling management system
- 一文带你了解BI的前世今身与企业数字化转型的关系
猜你喜欢
C language course setting: cinema ticket selling management system
快手、抖音、视频号交战内容付费
面试字节,过关斩将直接干到 3 面,结果找了个架构师来吊打我?
我国算力规模排名全球第二:计算正向智算跨越
How to solve the problem that easycvr changes the recording storage path and does not generate recording files?
The development of mobile IM based on TCP still needs to keep the heartbeat alive
NEW:Devart dotConnect ADO. NET
Use threejs to create geometry and add materials, lights, shadows, animations, and axes
企业级:Spire.Office for .NET:Platinum|7.7.x
error Couldn‘t find a package. JSON file in "your path“
随机推荐
MacBook安装postgreSQL+postgis
Containerd series - what is containerd?
Summary of scene design
The new project Galaxy token just announced by coinlist is gal
Online text line fixed length fill tool
[charging station]_ Secular wisdom_ Philosophical wisdom _
provide/inject
Longyuan war "epidemic" 2021 network security competition web easyjaba
What is the reason why the webrtc protocol video cannot be played on the easycvr platform?
WGS84 coordinate system, web Mercator, gcj02 coordinate system, bd09 coordinate system - brief introduction to common coordinate systems
Uni app common functions /api
Rust区块琏开发——签名加密与私钥公钥
As soon as I write the code, President Wang talks with me about the pattern all day
Interview summary: This is a comprehensive & detailed Android interview guide
About the recent experience of writing questions
CTF stegano practice stegano 9
Why can't all browsers on my computer open web pages
我就一写代码的,王总整天和我谈格局...
Rust blockchain development - signature encryption and private key public key
open graph协议