上一篇文章我们回顾了 MVVM 模式并了解了 Android Data Binding 的相关知识。那么这一章我们来实际做一个简单的基于 Android Data Binding 的 MVVM 架构的 app。
创建一个 Android 项目
我们先用 Android Studio 创建一个带有 Empty Activity 的项目:
自动生成的 MainActivity 如下:
package li.fyun.mvvm.view;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import li.fyun.mvvm.R;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".view.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello Word"
/>
</RelativeLayout>
增加对 Data Binding 的支持
在 app 的 build.gradle 中增加:
...
android {
...
dataBinding {
enabled = true
}
...
}
创建 Model
在子 package .model 中创建 Model 类 User:
package li.fyun.mvvm.model;
import java.util.Random;
/**
* Created by fyunli on 15/12/28.
*/
public class User {
private static final User[] users = new User[]{
new User("Andrea"), new User("Betty"), new User("Calvin"), new User("Daisy"), new User("Eason"),
new User("Frank"), new User("Gary"), new User("Halen"), new User("Iris"), new User("Java")
};
private String username;
private String portrait = "http://ww3.sinaimg.cn/large/620f1e7egw1ey8bjsbmr2j20b40b475e.jpg";
public User(String username) {
this.username = username;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPortrait() {
return portrait;
}
public void setPortrait(String portrait) {
this.portrait = portrait;
}
// just a sample logic
public static User getUser() {
int index = new Random().nextInt(3);
return users[index];
}
}
创建 ViewModel
然后在子 package .viewmodel 中创建 ViewModel 类 UserModel:
package li.fyun.mvvm.viewmodel;
/**
* Created by fyunli on 15/12/28.
*/
public interface ViewModel {
void destroy();
}
package li.fyun.mvvm.viewmodel;
import android.databinding.ObservableField;
import android.os.Parcel;
import android.os.Parcelable;
import li.fyun.mvvm.model.User;
/**
* Created by fyunli on 15/12/28.
*/
public class UserModel implements ViewModel, Parcelable {
public ObservableField<String> username = new ObservableField<>();
public ObservableField<String> portrait = new ObservableField<>();
public UserModel(User user) {
this.username.set(user.getUsername());
this.portrait.set(user.getPortrait());
}
@Override
public void destroy() {
}
// just a sample logic
public static UserModel laodUser() {
User user = User.getUser();
return new UserModel(user);
}
// use android parceable generator plugin to gen the code
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeSerializable(this.username);
dest.writeSerializable(this.portrait);
}
protected UserModel(Parcel in) {
this.username = (ObservableField<String>) in.readSerializable();
this.portrait = (ObservableField<String>) in.readSerializable();
}
public static final Creator<UserModel> CREATOR = new Creator<UserModel>() {
public UserModel createFromParcel(Parcel source) {
return new UserModel(source);
}
public UserModel[] newArray(int size) {
return new UserModel[size];
}
};
}
绑定 View 和 ViewModel
在 activity_main.xml 中声明 UserModel 变量 user, 并在 TextView 中用 @{user.username} 绑定属性:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<data>
<variable
name="user"
type="li.fyun.mvvm.viewmodel.UserModel"/>
</data>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".view.MainActivity">
<TextView
android:id="@+id/textview_username_label"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:text="Username:"
/>
<TextView
android:id="@+id/textview_username_field"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{user.username}"
android:layout_toRightOf="@id/textview_username_label"
tools:text="Vincent"
/>
</RelativeLayout>
</layout>
然后在 MainActivity 中绑定 View 和 ViewModel:
package li.fyun.mvvm.view;
import android.databinding.DataBindingUtil;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import li.fyun.mvvm.R;
import li.fyun.mvvm.databinding.ActivityMainBinding;
import li.fyun.mvvm.viewmodel.UserModel;
public class MainActivity extends AppCompatActivity {
ActivityMainBinding binding;
UserModel userModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
userModel = UserModel.laodUser();
binding.setUser(userModel);
}
}
展示一下成果
在模拟器中运行,效果如下:
增加一点新东西
我们希望在这个程序中能显示用户的头像。
首先我们在 layout 中先声明一个 ImageView 并绑定到 UserModel 的 portrait:
<ImageView
android:id="@+id/imageview_portraint"
android:layout_width="64dp"
android:layout_height="64dp"
android:layout_marginRight="32dp"
app:imageUrl="@{user.portrait}"/>
然后,我们要在 UserModel 中写一个 BindingAdapter 用于加载图像:
@BindingAdapter({"bind:imageUrl"})
public static void loadImage(ImageView view, String imageUrl) {
Glide.with(view.getContext())
.load(imageUrl)
.into(view);
}
别忘了在 app 的 build.gralde 中引入依赖:
compile 'com.github.bumptech.glide:glide:3.6.1'
并在 AndroidManifest.xml 中声明 INTERNET 访问权限:
<uses-permission android:name="android.permission.INTERNET"/>
运行程序,看一下效果:
处理屏幕旋转
这时候发现有什么问题吗?当你旋转屏幕的时候,显示的用户名会随机变化,这是应为 Activity Instance State 没有保存,在 MVVM 模式下,Instance State 的保存变得简单许多:
首先在 onSaveInstanceState 中保存:
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable(USER_MODEL, userModel);
}
然后在 onRestoreInstanceState(Bundle savedInstanceState) 或者 onCreate(Bundle savedInstanceState) 方法中取回保存的数据即可:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
if(savedInstanceState == null) {
userModel = UserModel.laodUser();
}else{
userModel = savedInstanceState.getParcelable(USER_MODEL);
}
binding.setUser(userModel);
}
打完,收工!
源代码在 Github 可找到。