最近学到android自定义控件,上次记录一个简单的自定义了一个显示图片控件,今天想做一个下拉刷新的控件,了解到Scorller类,它是android的帮助view滑动的一个帮助类,我也试着写了一个简单的ScorllLayout类,能使内部的view滑动,只是简单的封装了一下Scorller的功能,也是为下拉刷新控件做准备,记录一下。
package com.example.sosky.skytalk;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.FrameLayout;
import android.widget.Scroller;
/**
* Created by sOSky on 2017/11/21.
*/
public class ScrollLayout extends FrameLayout {
private Scroller mScorller;
public ScrollLayout(Context context){
super(context);
mScorller = new Scroller(context);
}
public ScrollLayout(Context context, AttributeSet attributeSet){
super(context,attributeSet);
mScorller = new Scroller(context);
}
public ScrollLayout(Context context,AttributeSet attributeSet,int style){
super(context,attributeSet,style);
mScorller = new Scroller(context);
}
//在view重绘时被调用
@Override
public void computeScroll() {
if (mScorller.computeScrollOffset()){
this.scrollTo(mScorller.getCurrX(),mScorller.getCurrY());
this.postInvalidate();
}
}
public void scrollTo(int y){
mScorller.startScroll(getScrollX(),getScrollY(),0,y,20000);
this.invalidate();
}
}
<com.example.sosky.skytalk.ScrollLayout
android:id="@+id/my_scrollLayout"
android:layout_width="wrap_content"
android:layout_height="300dp"
android:layout_below="@id/my_imageview">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="我们要开始滚动了!!!!"
android:textSize="30dp"/>
</com.example.sosky.skytalk.ScrollLayout>
其实主要函数只有两个,一个是computeScroll(),另外一个scrollTo()。computeScroll()是对view滑动重绘前时被调用,具体做的就是通过Scorller类让view滑动到应该滑动的位置(Scorller能够设置滑动时间,然后它来计算当前应当滑动到什么位置)。是否滑到终止也是由Scorller类的函数反馈的(computeScrollOffset())。
还有就是在两个函数刷新view的函数是不同的,虽然功能相同,他们在使用方式上同样也是不同的。
简洁的说 invalidate()只能在UI主线程中调用,而postinvalidate()可以在任何现成中调用。,因此在使用中注意调用函数的位置,避免出现异常。
有一个错误是我在自定义view中遇到的,Binary XML file line # : Error inflating class”,出现的原因是自定的view的构造函数有三个,在这里是
ScorllLayout(Context context);
ScorllLayout(Context context ,AttributeSet attributeSet);
ScorllLayout(CContext context,AttributeSet attributeSet,int style);
至少要实现前两个,如果你出现上面的异常,大多数时候是这个原因,其他原因可能就是引用路径有问题。