关键计算地方:
1.当前是上滑动还是下滑动(相对于屏幕) ,使用ev.getRawY()获得当前滑动位置在屏幕哪个地方
2. 计算文本客滑动到哪里即可停止, (行高*总文本行数)- (行高 * 最多显示行数) int sum = getLineHeight() * getLineCount() - getLineHeight() * getMaxLines();
代码:
import android.content.Context;
import android.text.method.ScrollingMovementMethod;
import android.util.AttributeSet;
import android.view.MotionEvent;/*** @Description: 可滑动的TextView, 并且解决了与 ScrollView等的滑动冲突*/
public class ScrollTextView extends android.support.v7.widget.AppCompatTextView {public ScrollTextView(Context context) {super(context);setMovementMethod(ScrollingMovementMethod.getInstance());}public ScrollTextView(Context context, AttributeSet attrs) {super(context, attrs);setMovementMethod(ScrollingMovementMethod.getInstance());}public ScrollTextView(Context context, AttributeSet attrs, int defStyleAttr) {super(context, attrs, defStyleAttr);setMovementMethod(ScrollingMovementMethod.getInstance());}float lastScrollY = 0;@Overridepublic boolean onTouchEvent(MotionEvent ev) {if (getLineCount() > getMaxLines()) {if (ev.getAction() == MotionEvent.ACTION_DOWN) {lastScrollY = ev.getRawY();} else if (ev.getAction() == MotionEvent.ACTION_MOVE) {//滑动到头并且还在继续上滑动,或者滑动到底部就不要再拦截了(有误差)int sum = getLineHeight() * getLineCount() - getLineHeight() * getMaxLines();//计算上次与本次差float diff = lastScrollY - ev.getRawY();if (diff>0){//下滑动并且到达了底部也不要处理了//底部这里用abs的原因是,因为计算sum的时候有些误差if (Math.abs(sum - getScrollY())<5) {getParent().requestDisallowInterceptTouchEvent(false);} else {getParent().requestDisallowInterceptTouchEvent(true);}}else if (diff<0){//上滑动if (getScrollY() == 0) {//上滑动并且已经到达了顶部就不要在处理了getParent().requestDisallowInterceptTouchEvent(false);} else {getParent().requestDisallowInterceptTouchEvent(true);}}lastScrollY = ev.getRawY();} else {getParent().requestDisallowInterceptTouchEvent(false);}}return super.onTouchEvent(ev);}
}
分享:
定时垂直滚动的textview:GitHub - paradoxie/AutoVerticalTextview: 垂直滚动的textview,继承自TextSwitcher,抽出一个依赖库供以后备用
左右对齐的TextView
GitHub - Giftedcat/JustifyTextView: 左右对齐的TextView,适配各种分辨率,完美实现UI需求
JustifyTextView 自定义TextView解决中文排版-CSDN博客