实现 TextView 单行竖向展示手动滚动
时间: 2024-12-02 21:18:38 浏览: 21
在Android开发中,如果你想要实现TextView单行竖向显示并支持手动滚动,通常会使用`ScrollView`包裹住`TextView`,因为`TextView`本身并不具备滚动功能。以下是简单的步骤:
1. 首先,在布局XML文件中创建一个`ScrollView`组件:
```xml
<ScrollView
android:id="@+id/scroll_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fillViewport="true">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="这里输入很长的文本..."
android:singleLine="false" <!-- 设置为false,使其可以超出一行 -->
android:ellipsize="marquee" <!-- 滑动到边缘时启用自动滚动 -->
android:focusable="true"
android:focusableInTouchMode="true"/>
</ScrollView>
```
2. 在对应的Activity或Fragment中设置滚动监听:
```java
TextView textView = findViewById(R.id.text_view);
textView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_UP) {
// 手指触摸屏幕开始或结束时停止滚动
textView.stopMarquee();
} else if (event.getAction() == MotionEvent.ACTION_MOVE) {
// 手指移动时,如果手指滑过整个宽度,则继续滚动
if (Math.abs(event.getX()) >= textView.getWidth()) {
textView.startMarquee();
}
}
return false; // 返回false以阻止默认处理
}
});
```
3. 当用户释放触摸时,`stopMarquee()`函数将停止自动滚动;当用户触摸移动超过TextView宽度时,`startMarquee()`会让滚动重新开始。
阅读全文
相关推荐


















