最简单的Android自定义View

最近项目需要用到一个很简洁的进度条,所以自定义一个

需要做的事情:

1.继承View

2.重写onDraw(Canvas c)方法

3.更新View

4.使用

开始

1.继承自View或VIew的子类

public class SlenderProgressBar extends View{

}

需要在构造器调用父类构造方法super(Context context, @Nullable AttributeSet attrs)

或者super(Context context, @Nullable AttributeSet attrs, int defStyleAttr)

不能只调用super(Context context)

原因未知

public SlenderProgressBar(Context context) {

        this(context,null);

    }

    public SlenderProgressBar(Context context, @Nullable AttributeSet attrs) {

        this(context, attrs,0);

    }

    public SlenderProgressBar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {

        super(context, attrs, defStyleAttr);

    }

2.重写onDraw(Canvas canvas)方法,画你想画的东西

@Override

    public void onDraw(Canvas canvas) {

        super.onDraw(canvas);

        //画矩形

       //getMeasuredWidth()获取View宽度

       //mProgress进度,length矩形长度

        float length =(mProgress/100)*getMeasuredWidth();

        //定义一个矩形

        RectF rectF=new RectF(0,0,length,getMeasuredHeight());

        //画

        canvas.drawRect(rectF,p);

    }

3.更新view

调用invalidate()方法,在自定义控件内定义方法

public void drawRect(float ratio){

mProgress=ratio;

    //每次更新进度后,也同时更新view

    invalidate();

}

4.使用

自定义控件使用时需要声明完整的包名路径

在xml中:

    android:layout_gravity="center"

    android:id="@+id/spb"

    android:layout_width="match_parent"

    android:layout_height="4dp"

    android:background="@color/colorAccent"/>

完整代码见:

https://github.com/YGLLL/CustemViewTest/tree/step1

下一次将为进度条加入动画特效

你可能感兴趣的:(最简单的Android自定义View)