Android新手必读的RecyclerView使用总结

时间:2021-03-30 20:01:23

RecyclerView比ListView要复杂一些,如果总结起来,使用方法也很清晰。希望我的总结能帮助到更多的Andoid爱好者。

Android新手必读的RecyclerView使用总结

1.依赖库

使用RecylerView需要Google支持库recyclerview-v7

2.RecylerView

作用:回收和定位屏幕上的View,列表项显示数据还是需要另外两个子类的支持:ViewHolder子类和Adapter子类。

  • setLayoutManager方法,需要LayoutManager的支持,LinearLayoutManger数值列表,GridLayoutManager网格列表。
  • setAdapter方法,设置RecylerView.Adapter
    FragmentBeatBoxBinding binding = DataBindingUtil
            .inflate(inflater, R.layout.fragment_beat_box, container, false);
    binding.recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 3));
    binding.recyclerView.setAdapter(new SoundAdapter(mBeatBox.getmSounds()));

3.RecylerView.ViewHolder

作用:容纳子项的View视图

  • 构造方法:调用super()传入总的布局视图,实例化视图组件
  • bind方法:传入数据模型,将模型的值传给组件
private class SoundHolder extends RecyclerView.ViewHolder{
    private ListItemSoundBinding mBinding;

    public SoundHolder(ListItemSoundBinding binding) {
        super(binding.getRoot());
        mBinding = binding;
        mBinding.setViewModel(new SoundViewModel(mBeatBox));
    }

    public void bind(Sound sound){
        mBinding.getViewModel().setSound(sound);
        mBinding.executePendingBindings();
    }
}

4.RecylerView.Adapter

作用:管理子项

  • 创建必要的ViewHolder
  • 绑定ViewHodler到模型层数据

RecylerView和Adapter会话:

  1. getItemCount(),询问数组列表包含对象个数
  2. onCreateViewHolder(ViewGoup, int)创建ViewHolder和要显示的视图
  3. 传入ViewHolder及其位置,调用onBindViewHolder(ViewHolder, int),找到目标位置的数据并绑定到ViewHolder视图上。

使用:

private class SoundAdapter extends RecyclerView.Adapter<SoundHolder>{

    private List<Sound> mSounds;

    public SoundAdapter(List<Sound> sounds) {
        this.mSounds = sounds;
    }

    @Override
    public SoundHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(getActivity());
        ListItemSoundBinding binding = DataBindingUtil
                .inflate(inflater, R.layout.list_item_sound, parent, false);
        return new SoundHolder(binding);
    }

    @Override
    public void onBindViewHolder(SoundHolder holder, int position) {
        Sound sound = mSounds.get(position);
        holder.bind(sound);
    }

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

项目的关键源码我上传到了github上。