1,实现效果
【1】scrollTo & scrrllBy的特点
-
实际上上面2个api滚动是的view绘制的内容,view本身并没有动
-
scrollTo当x传入正数往做移动.传入负数往右移动. (偏移量x = 0-i)
-
scrollBy 在上一次移动的基础上在移动X
2,实现逻辑
【1】创建一个类,继承view ,重写onMeasure 和 onDraw
public class LockView extends View {
public LockView(Context context, AttributeSet attrs) {
super(context, attrs);
}
//在这个方法里面测量当前view的大小
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
}
//往当前的view上画内容
@Override
protected void onDraw(Canvas canvas) {
//[1]由于背景我已经在布局中加上 所以只需要往当前的view上画 滑块就可以了
}
【2】MainActivity 的布局中声明使用自定义view
-
android:background="@drawable/lockviewbg" 设置了背景
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<com.xiaoshuai.lockview.LockView
android:id="@+id/lockView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/lockviewbg"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"
/>
</RelativeLayout>
【3】布局的绘制
-
LockView构造方法,BitmapFactory获取图片资源图片
//[1]获取背景图片和 滑动块的图
lockViewBg = BitmapFactory.decodeResource(getResources(), R.drawable.lockviewbg);
slideBg = BitmapFactory.decodeResource(getResources(), R.drawable.switch_button);
-
在onMeasure进行测量背景图片的大小
//在这个方法里面测量当前view的大小
@Override
protected void onMeasure(int widthMeasu