RecyclerView是什么
从Android 5.0开始,谷歌公司推出了一个用于大量数据展示的新控件RecylerView,可以用来代替传统的ListView,更加强大和灵活。
RecyclerView简介
RecyclerView就是一个控件,可以用来代替listview和gridview,使用方式差不多,都需要加载适配器。
RecyclerView优点
RecyclerView是support-v7包中的新组件,是一个强大的滑动组件,与经典的ListView相比,同样拥有item回收复用的功能。
RecyclerView的三种加载方式
// LinearLayoutManager manager = new LinearLayoutManager(this);
// manager.setOrientation(LinearLayoutManager.VERTICAL); //列表
// GridLayoutManager gridLayoutManager = new GridLayoutManager(this,3); //网格
StaggeredGridLayoutManager manager = new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL);
recyclerView.setLayoutManager(manager);
RecyclerView添加动画
DefaultItemAnimator defaultItemAnimator = new DefaultItemAnimator();
defaultItemAnimator.setAddDuration(2000);
defaultItemAnimator.setRemoveDuration(2000);
recyclerView.setItemAnimator(defaultItemAnimator);
RecyclerView分割线
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(this,DividerItemDecoration.VERTICAL);
// dividerItemDecoration.setDrawable(new ColorDrawable(234234));
recyclerView.addItemDecoration(dividerItemDecoration);
RecyclerView的万能适配器
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHoder> {
ArrayList<Integer> strings;
Context context;
public MyAdapter(ArrayList<Integer> strings,Context context)
{
this.strings = strings;
this.context = context;
}
@NonNull
@Override
public MyViewHoder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
//返回viewHolder
View itemView = LayoutInflater.from(context).inflate(R.layout.item_layout,null); //视图
MyViewHoder viewHoder = new MyViewHoder(itemView);
return viewHoder;
}
@Override
public void onBindViewHolder(@NonNull MyViewHoder myViewHoder, final int i) {
int hightValue =(int)Math.random()*801+300;
ViewGroup.LayoutParams layoutParams = (ViewGroup.LayoutParams) myViewHoder.imageView.getLayoutParams();
layoutParams.height = hightValue;
myViewHoder.imageView.setLayoutParams(layoutParams);
myViewHoder.imageView.setImageResource(strings.get(i));
myViewHoder.imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
strings.remove(i);
notifyItemRemoved(i); //更新
notifyItemRangeChanged(i,strings.size());
}
});
// myViewHoder.imageView.setOnLongClickListener(new View.OnLongClickListener() {
// @Override
// public boolean onLongClick(View v) {
//
// strings.add(R.mipmap.kk);
// notifyItemInserted(i);
// return true;
// }
// });
}
@Override
public int getItemCount() {
return strings.size();
}
class MyViewHoder extends RecyclerView.ViewHolder
{
ImageView imageView;
public MyViewHoder(@NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.text);
}
}
}