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