正在加載中LoadingView

在這裏插入圖片描述
loading.png

@SuppressLint("AppCompatCustomView")
public class LoadingView extends ImageView{

    private int rotateDegree = 0;

    private boolean mNeedRotate = false;

    public LoadingView(Context context) {
        this(context,null);
    }

    public LoadingView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);
    }

    public LoadingView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        //設置圖標
        setImageResource(R.mipmap.loading);
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        mNeedRotate = true;
        //綁定到window
        post(new Runnable() {
            @Override
            public void run() {
               rotateDegree += 30;
               rotateDegree = rotateDegree > 360 ? 0 : rotateDegree;
               //調用onDraw
               invalidate();
                if (mNeedRotate) {
                    //延時,100毫秒調用一次
                    postDelayed(this,100);
                }
            }
        });
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        //從window中解綁
        mNeedRotate = false;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        //第一個參數是旋轉角度,第二個是旋轉中心
        canvas.rotate(rotateDegree,getWidth()/2,getHeight()/2);
        super.onDraw(canvas);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章