Toolbar+RecyclerView进阶使用(仿淘宝列表、网格布局之间的切换)

Toolbar

ToolBar初始化

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolBar);
        toolbar.setTitle("");
        setSupportActionBar(toolbar);

        // 设置App Logo
        toolbar.setLogo(R.mipmap.dog);


        // 设置Menu
        toolbar.inflateMenu(R.menu.menu);

        /**
            要使用menu需重写onCreateOptionsMenu()方法
            要监听Menu需重写onOptionsItemSelected()方法
                                                        */
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

RecyclerView

第一次进入应用默认显示列表模式

        adapter = new MyAdapter(this,R.layout.list_item,models);

        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));

        mRecyclerView.setAdapter(adapter);
  • 1
  • 2
  • 3
  • 4
  • 5

点击toobar的menu进行模式切换,在toobar监听菜单的方法里进行逻辑判断

        /** 定义一个保存当前状态的变量 */

        switch (item.getItemId()){
            case R.id.item:

                /** 定义了两个常量,意义分别是列表模式,网格模式 */
                if(currentMode == MODE_GRID){

                    /** 动态替换图标,并把当前模式更改 */
                    item.setIcon(R.mipmap.list);
                    currentMode = MODE_LIST;

                    /** 调用适配器里重构布局的方法,并重新设置适配器 */
                    adapter.reBuildLayout(R.layout.grid_item);
                    mRecyclerView.setLayoutManager(new GridLayoutManager(this,2));
                    mRecyclerView.setAdapter(adapter);

                }else if(currentMode == MODE_LIST){

                    item.setIcon(R.mipmap.grid0);
                    currentMode = MODE_GRID;

                    adapter.reBuildLayout(R.layout.list_item);
                    mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
                    mRecyclerView.setAdapter(adapter);

                }


                break;

        }

        return super.onOptionsItemSelected(item);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34

适配器里的重构布局方法

    public void reBuildLayout(int layoutId){

        this.mLayoutResId = layoutId;

        notifyDataSetChanged();

    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

效果图

这里写图片描述 ······这里写图片描述

/**上面效果是优化过后的效果

            1.添加了分割线
            2.切换时保存当前的position

                                    */
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

源码

完整效果版代码

--------------------- 本文来自 Konfyt_Android 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/Konfyt_Android/article/details/52734866?utm_source=copy

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值