Step 1: override getItemViewType() method in adapter; add setType(int type) method
Step 2: three steps when clicking layout to switch pictures
- //Use this method to set type when clicking switch layout
- public void setType(int type) {
- this.type = type;
- }
- @Override
- //Which type of layout is used to get the current Item
- public int getItemViewType(int position) {
- return type;
- }
Step 3: in the onCreateViewHolder() method of adapter, switch the item layout according to the layout type you set
- if (goodsType==0){
- ivGoodsType.setImageResource(R.mipmap.good_type_grid);
- //1: Set layout type
- adapter.setType(1);
- //2: Set the corresponding layout manager
- recyclerView.setLayoutManager(new GridLayoutManager(context,2));
- //3: Refresh adapter
- adapter.notifyDataSetChanged();
- goodsType=1;
- }else {
- ivGoodsType.setImageResource(R.mipmap.good_type_linear);
- adapter.setType(0);
- recyclerView.setLayoutManager(new LinearLayoutManager(context));
- adapter.notifyDataSetChanged();
- goodsType=0;
- }
Next, we will know that the top picture appears at the bottom sliding position, and click the picture to realize the top function of RecyclerView;
- public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
- View baseView;
- if (viewType == 0) {
- baseView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_listview_goods_list, parent, false);
- LinearViewHolder linearViewHolder = new LinearViewHolder(baseView);
- return linearViewHolder;
- } else {
- baseView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_gridview_goods_list, parent, false);
- GridViewHolder gridViewHolder = new GridViewHolder(baseView);
- return gridViewHolder;
- }
- }
The top picture is not always displayed on the screen, but can only be displayed by sliding to a certain distance through monitoring; we need to rewrite the sliding monitoring of RecyclerView;
- //Set sliding monitor
- recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
- @Override
- public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
- super.onScrolled(recyclerView, dx, dy);
- RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
- if (layoutManager instanceof LinearLayoutManager) {
- LinearLayoutManager linearManager = (LinearLayoutManager) layoutManager;
- //Get the first visible location
- int firstVisibleItemPosition = linearManager.findFirstVisibleItemPosition();
- //Show top icons when sliding to more than 10
- if (firstVisibleItemPosition>10) {
- ivStick.setVisibility(View.VISIBLE);
- }else {
- ivStick.setVisibility(View.GONE);
- }
- }
- }
- });