Android必知必会-自定义Scrollbar样式
如果移动端访问不佳,请使用–>GitHub版
背景
设计师给的设计图完全依照 IOS 的标准来的,导致很多细节的控件都得自己重写,最近的设计图中有显示滚动条,Android 默认的滚动条样式(带描边)和设计图格格不入,无奈,只好研究下自定义 Scrollbar 样式。这里稍微整理下。
知识点
在ListView/ScrollView/RecyclerView中添加属性:
<!-- 情况A :垂直滚动条-->
android:scrollbars="vertical"
android:scrollbarTrackVertical="@drawable/xxx_vertical_track"
android:scrollbarThumbVertical="@drawable/xxx_vertical_thumb"
<!-- 情况B :水平滚动条-->
android:scrollbars="horizontal"
android:scrollbarTrackHorizontal="@drawable/xxx_horizontal_track"
android:scrollbarThumbHorizontal="@drawable/xxx_horizontal_thumb"
<!-- 其他通用的属性 -->
<!-- 1.定义滚动条的样式和位置 -->
android:scrollbarStyle="outsideInset"
<!-- 2.定义滚动条的大小,垂直时指宽度,水平时指高度 -->
android:scrollbarSize="4dp"
| 属性 | 效果 |
|---|---|
| scrollbarThumbVertical[Horizontal] | 短条 |
| scrollbarTrackVertical[Horizontal] | 长条,即背景 |
即scrollbaTrackxxx,scrollbarThumbxxx自定义的 xml 文件,放在Drawable中,track是指长条,thumb是指短条,然后再 xml 中定义短条和长条的样式。
需要注意
其中,scrollbaTrackxxx、scrollbarThumbxxx可以使用:
- Shape自定义 Drawable
- 图片
.9.png@color/xxx的方式使用颜色值
不可以直接使用#xxxxxx颜色值
android:scrollbarStyle
android:scrollbarStyle可以定义滚动条的样式和位置,可选值有insideOverlay、insideInset、outsideOverlay、outsideInset四种。
其中inside和outside分别表示是否在 view 的 padding 区域内,overlay和inset表示覆盖在 view 上或是插在 view 后面,所以四种值分别表示:
| 属性值 | 效果 |
|---|---|
| insideOverlay | 默认值,表示在padding区域内并且覆盖在view上 |
| insideInset | 表示在padding区域内并且插入在view后面 |
| outsideOverlay | 表示在padding区域外并且覆盖在view上 |
| outsideInset | 表示在padding区域外并且插入在view后面 |
Demo
下面是两个Demo:
color:
<color name="red_square">#CCFF6464</color>
<color name="transparent">#00000000</color>
drawable:scrollbar_vertical_thumb
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<!-- 填充 -->
<solid android:color="#66000000"/>
<!-- 圆角 -->
<corners android:radius="1dp" />
</shape>
Demo 1
layout:
android:scrollbarStyle="outsideOverlay"
android:scrollbarThumbVertical="@drawable/scrollbar_vertical_thumb"
<!--
scrollbarTrackVertical设为透明或者直接不设置即可
android:scrollbarTrackVertical="@color/transparent"
再次强调:scrollbarThumbVertical、scrollbarTrackVertical 不可以直接设置为颜色值,但可以使用@color的方式使用颜色值
-->
android:scrollbarSize="3dp"
android:scrollbars="vertical"
Demo 2
layout:
android:scrollbarStyle="outsideOverlay"
android:scrollbarThumbVertical="@color/red_square"
android:scrollbarSize="3dp"
android:scrollbars="vertical"
效果图
默认样式 :
Demo 1 :
Demo 2:
总结
在查资料的过程中,发现滚动条也可以使用代码来画,这里不做过多介绍,有兴趣的可以研究一下。
PS:
浙公网安备 33010602011771号