一,通过布局设置
<TextView
android:id="@+id/tv_content"
android:layout_width="match_parent"
android:layout_height="160dp"
android:layout_marginTop="10dp"
android:scrollbars="vertical"
android:textColor="@color/black"
android:textSize="24sp"
android:text="sdfsdfsdf"
android:background="@color/nav_bg"/>
其中最关键的就是 android:scrollbars="vertical" 。此外,还需在代码中做如下调用:
tvContent.setMovementMethod(ScrollingMovementMethod.getInstance());
这样,TextView就可以垂直滚动同时显示默认的滚动条了。
下面补充几个布局中的常见属性:
android:scrollbarFadeDuration="1000" 1秒内滚动条逐渐隐藏
android:scrollbarStyle="outsideOverlay" 滚动条的位置样式
android:scrollbarThumbVertical="@drawable/ic_launcher" //滑块的图片
android:scrollbarTrackVertical="@drawable/ic_launcher" //滑道的图片
ScrollBar由两部分组成,一个是Track(滑道),一个是Thumb(滑块)
二,通过代码实现滚动并显示滚动条
正常来说,通过代码创建TextView并实现滚动很简单,只是把刚才xml的属性设置通过java代码来实现即可;但是写完后你会发现虽然可以滚动了,但是无法显示滚动条。恼火了很久,也尝试了很多方法,最终找到了偏方。
因为似乎从Api 21开始,智能通过布局文件设置android:scrollbars="vertical"显示滚动条,无法通过代码实现了。
但是偏方如下:
1:先定义一个样式,这样就间接实现了通过布局实现滚动;
<style name="ViewWithScrollbars">
<item name="android:scrollbars">vertical</item>
</style>
2:通过系统版本判断动态创建TextView并引用刚才创建的样式;
TextView tv = new TextView(this);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
// This will actually work for API 21 and above.
ContextThemeWrapper ctw = new ContextThemeWrapper(this, R.style.ViewWithScrollbars);
tv = new TextView(ctw);
} else {
tv = new TextView(this, null, 0, R.style.ViewWithScrollbars);
}
rl_content.addView(tv);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
tv.setLayoutParams(params);
3:给创建出来的TextView设置必要的垂直滚动相关的属性
Log.e("yin","执行了滚动");
//必须,垂直滚动,与布局中的scrollbars="vertical"等价
tv.setVerticalScrollBarEnabled(true);
//非必须,滚动条的位置样式
tv.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
//非必须,滚动条的隐藏时长
tv.setScrollBarFadeDuration(1000);
//非必须
tv.setSingleLine(false);
//非必须,是否允许滚动条隐藏
tv.setVerticalFadingEdgeEnabled(true);
//必须
tv.setMovementMethod(ScrollingMovementMethod.getInstance());
//此外,还可以设置滚动条的样式,宽度等等?
参考文章: