一、MVVM
(1)使用dataBinding实现双向绑定
- 在build.gradle的android内部添加
dataBinding{
enabled = true
}
- 布局文件最外层根节点是layout
- <data>标签做数据绑定
- <variable>放置变量名称和变量类型
- name变量名称,type变量类型
- onClick:设置点击事件
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<data>
<variable
name="user"
type="com.ee.cp.http.bean.User" />
<variable
name="mainActivity"
type="com.ee.cp.MainActivity" />
</data>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
user.imgUrl="@{user.imgUrl}"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_centerHorizontal="true"
tools:ignore="ContentDescription" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:layout_marginTop="250dp"
android:layout_marginBottom="15dp"
android:onClick="@{() -> mainActivity.onClickListenerUsername(user)}"
android:text="@{user.username}"
android:textColor="#555555"
android:textSize="18sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_marginTop="250dp"
android:layout_marginEnd="15dp"
android:onClick="@{() -> mainActivity.onClickListenerPassword()}"
android:text="@{user.password}"
android:textColor="#999999"
android:textSize="18sp"
tools:ignore="RelativeOverlap" />
</RelativeLayout>
</layout>
- User数据实体类
- BaseObservable
notifyPropertyChanged():更新指定变量
notifyChange():更新ViewModel所有数据 - @Bindable:创建对应的ID变量
- @BindingAdapter("user.imgUrl"):设置自定义属性,可以覆盖系统原生属性
public class User extends BaseObservable {
private String imgUrl;
private String username;
private String password;
@Bindable
public String getImgUrl() {
return imgUrl;
}
public void setImgUrl(String imgUrl) {
this.imgUrl = imgUrl;
notifyPropertyChanged(BR.imgUrl);
}
@BindingAdapter("user.imgUrl")
public static void setImgUrl(ImageView imageView, String url) {
Glide.with(imageView.getContext()).load(url).into(imageView);
}
@Bindable
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
notifyPropertyChanged(BR.username);
}
@Bindable
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
//更新指定变量
notifyPropertyChanged(BR.password);
}
public void setUser(String imgUrl, String username, String password) {
this.imgUrl = imgUrl;
this.username = username;
this.password = password;
//更新全部
notifyChange();
}
}
- ObservableField:只设置一次数据,当数据发生变化时,自动更新视图。
public class User {
private ObservableField<String> imgUrl = new ObservableField<>();
private ObservableField<String> username = new ObservableField<>();
private ObservableField<String> password = new ObservableField<>();
public ObservableField<String> getImgUrl() {
return imgUrl;
}
@BindingAdapter("user.imgUrl")
public static void setImgUrl(ImageView imageView, String url) {
Glide.with(imageView.getContext()).load(url).into(imageView);
}
public ObservableField<String> getUsername() {
return username;
}
public ObservableField<String> getPassword() {
return password;
}
}
- 在Activity中设置数据显示
public class MainActivity extends AppCompatActivity {
private User user;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
binding.setMainActivity(this);
user = new User();
binding.setUser(user);
user.getImgUrl().set("https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=3064617598,3378545092&fm=26&gp=0.jpg");
user.getUsername().set("昵称");
user.getPassword().set("密码");
}
public void onClickListenerUsername(User user) {
Toast.makeText(getApplicationContext(), "username:" + user.getUsername().get(), Toast.LENGTH_SHORT).show();
user.getUsername().set("修改昵称");
}
public void onClickListenerPassword() {
Toast.makeText(getApplicationContext(), "password:" + user.getPassword().get(), Toast.LENGTH_SHORT).show();
user.getPassword().set("修改密码");
}
}
(2)在RecyclerView中使用dataBinding
- 创建适配器RecyclerViewAdapter
- 在ViewHolder中设置get、set方法
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
private int variableId;
private List<User> list;
private LayoutInflater inflater;
public RecyclerViewAdapter(Context context, int variableId, List<User> list) {
this.variableId = variableId;
this.list = list;
inflater = LayoutInflater.from(context);
}
@NonNull
@Override
public RecyclerViewAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
ItemViewBinding binding = DataBindingUtil.inflate(inflater, R.layout.item_view, parent, false);
ViewHolder viewHolder = new ViewHolder(binding.getRoot().getRootView());
viewHolder.setBinding(binding);
return viewHolder;
}
@Override
public void onBindViewHolder(@NonNull RecyclerViewAdapter.ViewHolder holder, int position) {
holder.getBinding().setVariable(variableId, list.get(position));
//强制绑定操作马上执行
holder.getBinding().executePendingBindings();
}
@Override
public int getItemCount() {
return list.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
private ItemViewBinding binding;
public ViewHolder(@NonNull View itemView) {
super(itemView);
}
public void setBinding(ItemViewBinding binding) {
this.binding = binding;
}
public ItemViewBinding getBinding() {
return binding;
}
}
}
- 在代码中调用
public void showRecycler() {
//设置布局管理器
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
binding.recyclerView.setLayoutManager(linearLayoutManager);
RecyclerViewAdapter adapter = new RecyclerViewAdapter(this, BR.user, list);
binding.recyclerView.setAdapter(adapter);
}
(3)在ViewPager中使用dataBinding
- 创建适配器
public class ViewPagerAdapter extends PagerAdapter {
private int variableId;
private List<User> list;
private LayoutInflater inflater;
public ViewPagerAdapter(Context context, int variableId, List<User> list) {
this.variableId = variableId;
this.list = list;
inflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return list.size();
}
//判断初始化返回的Object是不是一个View对象
@Override
public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
ViewDataBinding binding = (ViewDataBinding) object;
return view == binding.getRoot();
}
//初始化显示的条目对象
@NonNull
@Override
public Object instantiateItem(@NonNull ViewGroup container, int position) {
ViewDataBinding binding = DataBindingUtil.inflate(inflater, R.layout.item_view, container, false);
binding.setVariable(variableId, list.get(position));
return binding;
}
//销毁条目对象
@Override
public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
ViewDataBinding binding = (ViewDataBinding) object;
container.removeView(binding.getRoot());
}
}
- 在代码中调用显示ViewPager
private void showViewPager() {
ViewPagerAdapter adapter = new ViewPagerAdapter(this, BR.user, list);
binding.viewPager.setAdapter(adapter);
}
(4)ViewStub与include使用dataBinding
- 在xml中使用ViewStub
<ViewStub
android:id="@+id/view_stub"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout="@layout/view_stub"/>
- 在代码中调用设置view_stub数据
View inflate = Objects.requireNonNull(binding.viewStub.getViewStub()).inflate();
ViewStubBinding viewStubBinding = DataBindingUtil.getBinding(inflate);
viewStubBinding.setUser(user);
- 在xml文件中将ViewModel直接传入到下一个xml文件
<include
layout="@layout/layout_include"
bind:user="@{user}"/>