当前位置:网站首页>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<>();
}
边栏推荐
- Threejs clicks the scene object to obtain object information, and threejs uses raycaster to pick up object information
- Soul 3: what is interface testing, how to play interface testing, and how to play interface automation testing?
- An elegant program for Euclid‘s algorithm
- EasyCVR平台出现WebRTC协议视频播放不了是什么原因?
- 【UNIAPP】系统热更新实现思路
- Use Firefox browser to quickly pick up Web image materials
- Ctfshow 2022 Spring Festival welcome (detailed commentary)
- Laravel8 export excel file
- This article takes you to understand the relationship between the past and present of Bi and the digital transformation of enterprises
- 小程序中实现文章的关注功能
猜你喜欢

Common features of ES6

测试开发是什么?为什么现在那么多公司都要招聘测试开发?

Is there a sudden failure on the line? How to make emergency diagnosis, troubleshooting and recovery

An elegant program for Euclid‘s algorithm

小程序中实现文章的关注功能

Differences among 10 addressing modes

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

Clickhouse materialized view

ActiveReportsJS 3.1 VS ActiveReportsJS 3.0

Containerd series - what is containerd?
随机推荐
What is the reason why the webrtc protocol video cannot be played on the easycvr platform?
UI automation test farewell to manual download of browser driver
Behavior perception system
【虚幻引擎UE】打包报错出现!FindPin错误的解决办法
快手、抖音、视频号交战内容付费
Enterprise level: spire Office for . NET:Platinum|7.7. x
How to use jedis of redis
ClickPaaS低代码平台
“金九银十”是找工作的最佳时期吗?那倒未必
Containerd series - what is containerd?
MindFusion. Virtual Keyboard for WPF
Clickhouse synchronization MySQL (based on materialization engine)
[wp]bmzclub writeup of several questions
Realize the attention function of the article in the applet
优先使用对象组合,而不是类继承
Special Edition: spreadjs v15.1 vs spreadjs v15.0
Possible stack order of stack order with length n
Online sql to excel (xls/xlsx) tool
Longyuan war "epidemic" 2021 network security competition web easyjaba
[charging station]_ Secular wisdom_ Philosophical wisdom _