当前位置:网站首页>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<>();
}
边栏推荐
- Mixed compilation of C and CC
- ActiveReportsJS 3.1 VS ActiveReportsJS 3.0
- JVM garbage collection
- 北京程序员的真实一天!!!!!
- mysql的七种join连接查询
- Threejs realizes rain, snow, overcast, sunny, flame
- 一文带你了解BI的前世今身与企业数字化转型的关系
- 技术教程:如何利用EasyDSS将直播流推到七牛云?
- [charging station]_ Secular wisdom_ Philosophical wisdom _
- Threejs implements labels and displays labels with custom styles
猜你喜欢

为什么百度、阿里这些大厂宁愿花25K招聘应届生,也不愿涨薪5K留住老员工?

IronXL for . NET 2022.6

Ctfshow web entry code audit
![[wp][introduction] brush weak type questions](/img/d0/9eb3ade701057837d98e4a20082a10.png)
[wp][introduction] brush weak type questions

基于TCP的移动端IM即时通讯开发仍然需要心跳保活

企业级:Spire.Office for .NET:Platinum|7.7.x

About the recent experience of writing questions

Interview summary: This is a comprehensive & detailed Android interview guide

【UNIAPP】系统热更新实现思路

Official announcement! The third cloud native programming challenge is officially launched!
随机推荐
C language course setting: cinema ticket selling management system
Interview summary: This is a comprehensive & detailed Android interview guide
特殊版:SpreadJS v15.1 VS SpreadJS v15.0
An elegant program for Euclid‘s algorithm
基于TCP的移动端IM即时通讯开发仍然需要心跳保活
学习MVVM笔记(一)
Enterprise level: spire Office for . NET:Platinum|7.7. x
IronXL for .NET 2022.6
技术教程:如何利用EasyDSS将直播流推到七牛云?
[wp]bmzclub writeup of several questions
【虚幻引擎UE】实现测绘三脚架展开动画制作
NEW:Devart dotConnect ADO.NET
“金九银十”是找工作的最佳时期吗?那倒未必
Kwai, Tiktok, video number, battle content payment
Differences among 10 addressing modes
Threejs implements labels and displays labels with custom styles
Threejs Internet of things, 3D visualization of farms (I)
A应用唤醒B应该快速方法
FFmepg使用指南
长度为n的入栈顺序的可能出栈顺序