简单实现RecyclerView嵌套RecyclerView
2017-03-28 本文已影响4555人
楷桐
Linearlayoutmanager RecyclerView嵌套GridLayoutManager RecyclerView
布局方式:以一个GridLayoutManager的recyclerview作为Linearlayoutmanager RecyclerView的itemview
MainRecyclerAdapter.java
public class MainRecyclerAdapter extends RecyclerView.Adapter<MainRecyclerAdapter.ViewHolder> {
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_view_main, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.mButton.setText("Item " + position);
if(holder.mRecyclerView.getAdapter()==null) {
holder.mRecyclerView.setAdapter(new GridAdapter());
}/*else {
holder.mRecyclerView.getAdapter().notifyDataSetChanged();
}*/
}
@Override
public int getItemCount() {
return 10;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public final AppCompatButton mButton;
public final RecyclerView mRecyclerView;
public ViewHolder(View itemView) {
super(itemView);
mButton = (AppCompatButton) itemView.findViewById(R.id.button);
mRecyclerView = (RecyclerView) itemView.findViewById(R.id.recyclerView);
RecyclerView.LayoutManager manager = new GridLayoutManager(itemView.getContext(), 4);
manager.setAutoMeasureEnabled(true);
mRecyclerView.setLayoutManager(manager);
}
}
}
需要注意的是GridLayoutManager要设置setAutoMeasureEnabled(true)成自适应高度***
onBindViewHolder 中需要判断item中recyclerview是否已经设置适配器,重复设置会导致滑动不流畅***
GridAdapter.java
public class GridAdapter extends RecyclerView.Adapter<GridAdapter.ViewHolder> {
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_view_grid, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.mTextView.setText("Grid "+position);
}
@Override
public int getItemCount() {
return 8;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public final AppCompatTextView mTextView;
public ViewHolder(View itemView) {
super(itemView);
mTextView= (AppCompatTextView) itemView.findViewById(R.id.textView);
}
}
}