Android的Databinding-RecyleView绑定
1 public class UserAdapter extends RecyclerView.Adapter<UserAdapter.UserHolder> { 2 private static final int USER_COUNT = 10; 3 4 @NonNull 5 private List<User> mUsers; 6 7 public UserAdapter() { 8 mUsers = new ArrayList<>(10); 9 for (int i = 0; i < USER_COUNT; i ++) { 10 User user = new User(Randoms.nextFirstName(), Randoms.nextLastName()); 11 mUsers.add(user); 12 } 13 } 14 15 public static class UserHolder extends RecyclerView.ViewHolder { 16 private UserItemBinding mBinding; 17 18 public UserHolder(View itemView) { 19 super(itemView); 20 mBinding = DataBindingUtil.bind(itemView); 21 } 22 23 public void bind(@NonNull User user) { 24 mBinding.setUser(user); 25 } 26 } 27 28 @Override 29 public UserHolder onCreateViewHolder(ViewGroup viewGroup, int i) { 30 View itemView = LayoutInflater.from(viewGroup.getContext()) 31 .inflate(R.layout.user_item, viewGroup, false); 32 return new UserHolder(itemView); 33 } 34 35 @Override 36 public void onBindViewHolder(UserHolder holder, int position) { 37 holder.bind(mUsers.get(position)); 38 } 39 40 @Override 41 public int getItemCount() { 42 return mUsers.size(); 43 } 44 }