RecyclerView绑定

ItemData类

public class ItemData {
    public ItemData() {
    }
    public ItemData(String name) {
        this.name = name;
    }
    private String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

item.xml 布局



    
        
    
    
        
    

BindingViewHolder 类

public class BindingViewHolder extends RecyclerView.ViewHolder {

    private T mBinding;

    public BindingViewHolder(T binding) {
        super(binding.getRoot());
        mBinding = binding;
    }

    public T getBinding() {
        return mBinding;
    }
}

MyAdapter 类

public class MyAdapter extends RecyclerView.Adapter> {

        private List list;

        public MyAdapter() {
            list = new ArrayList<>();
            for (int i = 0; i < 10; i++)
                list.add(new ItemData(i + ""));
        }

        @Override
        public BindingViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            ItemBinding binding
                    = DataBindingUtil.inflate(
                    LayoutInflater.from(parent.getContext()),
                    item, parent, false);
            return new BindingViewHolder(binding);
        }

        @Override
        public void onBindViewHolder(BindingViewHolder holder, int position) {

            holder.getBinding().setItem(list.get(position));
            // 立即设值
            holder.getBinding().executePendingBindings();
        }

        @Override
        public int getItemCount() {
            return list.size();
        }
    }

Activity

public class RecyclerViewDemo extends AppCompatActivity {
    RecyclerViewDemoBinding mBinding;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = DataBindingUtil.setContentView(this, R.layout.recycler_view_demo);
        mBinding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        mBinding.recyclerView.setAdapter(new MyAdapter());
    }
}

你可能感兴趣的:(RecyclerView绑定)