本文共 3804 字,大约阅读时间需要 12 分钟。
package zhangphil.test;import android.databinding.BaseObservable;import android.databinding.Bindable;/** * Created by Phil on 2017/9/4. */public class User extends BaseObservable { private int id; private String name; public void setId(int id) { this.id = id; notifyPropertyChanged(BR.id); } @Bindable public int getId() { return id; } public void setName(String name) { this.name = name; notifyPropertyChanged(BR.name); } @Bindable public String getName() { return name; }}
写一个适配器需要的item布局,item.xml:
测试的MainActivity.java:
package zhangphil.test;import android.app.ListActivity;import android.content.Context;import android.databinding.DataBindingUtil;import android.databinding.ViewDataBinding;import android.os.Bundle;import android.support.annotation.LayoutRes;import android.support.annotation.NonNull;import android.support.annotation.Nullable;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ArrayAdapter;import android.widget.ListView;import java.util.ArrayList;import static zhangphil.test.BR.user;public class MainActivity extends ListActivity { private ArrayListmItems; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //构造若干测试数据源 mItems = new ArrayList(); for (int i = 0; i < 100; i++) { User u = new User(); u.setId(i); u.setName("zhangphil @ " + i); mItems.add(u); } ArrayAdapter mAdapter = new ItemAdapter(this, R.layout.item); setListAdapter(mAdapter); } //每一次点击ListView,id加1,name后面追加系统毫秒时间字符串 //可以看到,这里不再使用Android的notifyDataSetChanged() 即可实时更新View数据 @Override protected void onListItemClick(ListView l, View v, int position, long id) { //取出原来的数据 int Id = mItems.get(position).getId(); String name = mItems.get(position).getName(); //在原来的数据上,id加1。name后面追加点击的时间 mItems.get(position).setId(Id + 1); mItems.get(position).setName(name + System.currentTimeMillis() + "\n"); } private class ItemAdapter extends ArrayAdapter { private Context context; private int resId; public ItemAdapter(@NonNull Context context, @LayoutRes int resource) { super(context, resource); this.context = context; this.resId = resource; } @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { //Android数据绑定的关键 ViewDataBinding binding; if (convertView == null) { binding = DataBindingUtil.inflate(LayoutInflater.from(context), resId, parent, false); convertView = binding.getRoot(); convertView.setTag(binding); } else { binding = (ViewDataBinding) convertView.getTag(); } binding.setVariable(user, getItem(position)); return convertView; } @Nullable @Override public User getItem(int position) { return mItems.get(position); } @Override public int getCount() { return mItems.size(); } }}
代码运行结果:
附录: 1,《Android官方DataBinding(三):RecyclerView 使用ViewDataBinding更新数据》链接:http://blog.csdn.net/zhangphil/article/details/77367432