版权声明:本文为博主原创文章,未经博主允许不得转载。
一、居中方法
Android自带的toolbar有设置title的功能,但是设置的title都是居左的,但是很多需求都是要title居中,主要的方法就是:不使用setTitle,而是在toolBar的xml定义中插入一个TextView,然后设置其layout_gravity为center,它就在正中间了。。
1、定义toolbar的xml文件
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
具体代码中使用toolbar
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
3、修改toolbar的返回按钮图标
在toolbar里面添加如下几句话,
- 1
- 2
- 3
- 1
- 2
- 3
全部xml
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
效果
4、修改一些属性
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
效果如下:
二、注意事项
这些方法很简单,网上的处理一大推,这边主要讲解的是一些注意事项。
1、定义toolbar的时候,尽量使用
- 1
- 2
- 3
- 1
- 2
- 3
而不是
- 1
- 2
- 1
- 2
因为当toolbar里面的textView的字体太大的时候,第一种方法能够包裹住,而第二种方法字体就会显示不全。如下图所示
这是使用第一种方法的:
这是使用第二种方法的:
2、textview尽量使用android:singleLine="true"
这个不解释了。
3、让原始的toolbar的title不显示,可以使用
- 1
- 1
或者
- 1
- 1
4、TextView尽量直接包在ToolBar下面,布局使用android:layout_gravity="center"
如果TextView还在另外一个布局里面,例如:
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
则title会减去toolbar那个返回按钮的宽度再让title居中,效果会是这样的:
就是不居中了。