TextView实现从上到下自动滚动效果
今天有个需求是要一个TextView自动滚动的效果。
刚开始试过使用TextView 的Padding或Layout_margin,虽然可以实现,但是感觉很麻烦,判断什么时候达到底部不容易,并且移植性不高。
后面发现使用ScrollView包裹TextView,使用ScrollView的scrollTo的方法就能实现
但是你要判断TextView是否可以滑动,是否已经达到底部。
我这里自己写了一个AutoScrollView,你只要使用这个类就可以实现TextView自动滚动了。
TextView实现滚动效果
这里有手动滑动了一下所以有了一下卡顿的效果,正常滚动是显示比较正常的。
AutoScrollView的代码
package com.nsd.lwx.autoscrolltextview;
/**
* Created by lWX537240 on 2018/3/14.
*/
import android.content.Context;
import android.graphics.Canvas;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ScrollView;
/**
* 监听ScrollView滚动到顶部或者底部做相关事件拦截
*/
public class AutoScrollView extends ScrollView {
private boolean isScrolledToTop = true; // 初始化的时候设置一下值
private boolean isScrolledToBottom = false;
private int paddingTop = 0;
private final int MSG_SCROLL = 10;
private final int MSG_SCROLL_Loop = 11;
private boolean scrollAble = false;//是否能滑动
//三个可设置的属性
private boolean autoToScroll = true; //是否自动滚动
private boolean scrollLoop = false; //是否循环滚动
private int fistTimeScroll = 5000;//多少秒后开始滚动,默认5秒
private int scrollRate = 50;//多少毫秒滚动一个像素点
public AutoScrollView(Context context) {
this(context, null);
}
public AutoScrollView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public AutoScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
this(context, attrs, defStyleAttr, 0);
}
public AutoScrollView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
private ISmartScrollChangedListener mSmartScrollChangedListener;
/**
* 定义监听接口
*/
public interface ISmartScrollChangedListener {
void onScrolledToBottom(); //滑动到底部
void onScrolledToTop();//滑动到顶部
}
//设置滑动到顶部或底部的监听
public void setScanScrollChangedListener(ISmartScrollChangedListener smartScrollChangedListener) {
mSmartScrollChangedListener = smartScrollChangedListener;
}
//ScrollView内的视图进行滑动时的回调方法,据说是API 9后都是调用这个方法,但是我测试过并不准确
@Override
protected void onOverScrolled(int scrollX, int scrollY, boolean clampedX, boolean clampedY) {
super.onOverScrolled(scrollX, scrollY, clampedX, clampedY);
if (scrollY == 0) {
isScrolledToTop = clampedY;
isScrolledToBottom = false;
} else {
isScrolledToTop = false;
isScrolledToBottom = clampedY;//系统回调告诉你什么时候滑动到底部
}
notifyScrollChangedListeners();
}
int lastY;
//触摸事件
@Override
public boolean onTouchEvent(MotionEvent event) {
int y = (int) event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// 记录触摸点坐标
lastY = y;
break;
case MotionEvent.ACTION_MOVE:
// 计算偏移量
int offsetY = y - lastY;
// 在当前left、top、right、bottom的基础上加上偏移量
paddingTop = paddingTop - offsetY / 10;
//不要问我上面10怎么来的,我大概估算的,正常一点应该是7或8吧,我故意让手动滑动的时候少一丢
scrollTo(0, paddingTop);
break;
}
return true;
}
//ScrollView内的视图进行滑动时的回调方法,据说是API 9前都是调用这个方法,我新版的SDK也是或回调这个方法
@Override
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
super.onScrollChanged(l, t, oldl, oldt);
// if (android.os.Build.VERSION.SDK_INT < 9) { // API 9及之后走onOverScrolled方法监听,
if (getScrollY() == 0) {
isScrolledToTop = true;
isScrolledToBottom = false;
} else if (getScrollY() + getHeight() - getPaddingTop() - getPaddingBottom() == getChildAt(0).getHeight()) {
isScrolledToBottom = true;
isScrolledToTop = false;
} else {
isScrolledToTop = false;
isScrolledToBottom = false;
}
notifyScrollChangedListeners();
// }
}
//判断是否滑动到底部或顶部
private void notifyScrollChangedListeners() {
if (isScrolledToTop) {
if (mSmartScrollChangedListener != null) {
mSmartScrollChangedListener.onScrolledToTop();
}
} else if (isScrolledToBottom) {
mHandler.removeMessages(MSG_SCROLL);
if (!scrollLoop) {
scrollAble = false;
}
if (scrollLoop) {
mHandler.sendEmptyMessageDelayed(MSG_SCROLL_Loop, fistTimeScroll);
}
if (mSmartScrollChangedListener != null) {
mSmartScrollChangedListener.onScrolledToBottom();
}
}
}
//handler
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case MSG_SCROLL:
if (scrollAble && autoToScroll) {
scrollTo(0, paddingTop);
paddingTop += 1;
mHandler.removeMessages(MSG_SCROLL);
mHandler.sendEmptyMessageDelayed(MSG_SCROLL, scrollRate);
}
break;
case MSG_SCROLL_Loop:
paddingTop = 0;
autoToScroll = true;
mHandler.sendEmptyMessageDelayed(MSG_SCROLL, fistTimeScroll);
}
}
};
//获取子View和ScrollView的高度比较,决定是否能够滑动View
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
View childAt = getChildAt(0);
int childMeasuredHeight = childAt.getMeasuredHeight(); //获取子控件的高度
int measuredHeight = getMeasuredHeight();//获取ScrollView的高度
// Log.e("onMeasure", "childMeasuredHeight:" + childMeasuredHeight + " ,measuredHeight:" + measuredHeight);
if (childMeasuredHeight > measuredHeight) { //如果子控件的高度大于父控件才需要滚动
scrollAble = true;
paddingTop = 0;
mHandler.sendEmptyMessageDelayed(MSG_SCROLL, fistTimeScroll);
} else {
scrollAble = false;
}
}
//设置是否自动滚动
public void setAutoToScroll(boolean autoToScroll) {
this.autoToScroll = autoToScroll;
}
//设置第一次开始滚动的时间
public void setFistTimeScroll(int fistTimeScroll) {
this.fistTimeScroll = fistTimeScroll;
mHandler.removeMessages(MSG_SCROLL);
mHandler.sendEmptyMessageDelayed(MSG_SCROLL, fistTimeScroll);
}
//设置滚动的速率,多少毫秒滚动一个像素点
public void setScrollRate(int scrollRate) {
this.scrollRate = scrollRate;
}
//设置是否循环滚动
public void setScrollLoop(boolean scrollLoop) {
this.scrollLoop = scrollLoop;
}
}
项目的其他代码
1.布局文件activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView Top" />
<com.nsd.lwx.autoscrolltextview.AutoScrollView
android:id="@+id/scrollView"
android:layout_width="match_parent"
android:layout_height="100dp">
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusable="true"
android:gravity="center"
android:text="Hello World!"
android:textSize="25dp" />
</com.nsd.lwx.autoscrolltextview.AutoScrollView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView Bottom" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="setLongText"
android:text="set Long Text"
android:textAllCaps="false" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="setShortText"
android:text="set Short Text"
android:textAllCaps="false" />
</LinearLayout>
2.MainActivity的java代码
package com.nsd.lwx.autoscrolltextview;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
TextView textView;
AutoScrollView autoScrollView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
initData();
initEvent();
}
private void initView() {
textView = findViewById(R.id.textView);
autoScrollView = findViewById(R.id.scrollView);
}
private void initData() {
autoScrollView.setAutoToScroll(true);//设置可以自动滑动
autoScrollView.setFistTimeScroll(2000);//设置第一次自动滑动的时间
autoScrollView.setScrollRate(50);//设置滑动的速率
autoScrollView.setScrollLoop(false);//设置是否循环滑动
}
// 监听是否达到头部或底部
private void initEvent() {
autoScrollView.setScanScrollChangedListener(new AutoScrollView.ISmartScrollChangedListener() {
@Override
public void onScrolledToBottom() {
Toast.makeText(MainActivity.this, "底部", Toast.LENGTH_SHORT).show();
}
@Override
public void onScrolledToTop() {
Toast.makeText(MainActivity.this, "顶部", Toast.LENGTH_SHORT).show();
}
});
}
// 给文本设置长字符串
public void setLongText(View view) {
textView.setText("1aaaaaaaaaaa\n2aaaaaaaaaaa\n3aaaaaaaaaaa\n4aaaaaaaaaaa\n5aaaaaaaaaaa\n" +
"6aaaaaaaaaaa\n7aaaaaaaaaaa\n8aaaaaaaaaaa\n9aaaaaaaaaaa\n10aaaaaaaaaaa\n" +
"11aaaaaaaaaaa\n12aaaaaaaaaaa\n13aaaaaaaaaaa\n14aaaaaaaaaaa\n15aaaaaaaaaaa");
}
// 给文本设置短字符串
public void setShortText(View view) {
textView.setText("1aaaaaaaaaaa\n2aaaaaaaaaaa");
}
}
再看一下滚动的效果:
到这里这个实现自动滑动的TextView就简单实现了。
这里有人也许会有疑问:如果ScrollView的height是match_parent,TextView的height也是match_parent,那么这个滚动效果有效吗?
其实是有效的,测量布局和窗体布局大小并不是绝对的相同,如果内容超出了窗体大小,测量高度也是会超出窗体大小的,我已经试验过了。