Android中ClipDrawable的使用和自定義ProgressBar
阿新 • • 發佈:2019-02-16
package com.example.ztest2; import java.lang.ref.WeakReference; import android.content.Context; import android.content.res.TypedArray; import android.graphics.drawable.ClipDrawable; import android.os.Handler; import android.os.Message; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.FrameLayout; import android.widget.ImageView; public class YXClipProgress extends FrameLayout{ /** * ClipDrawable-level的最大值,範圍在0-10000之間,0 不顯示,10000充分顯示 * 可以類比progress 即progress = MAX_PROGRESS/100; */ private static final int MAX_PROGRESS = 10000; /* 是否自動增加進度 */ private boolean auto_runing; private static final int MESSAGE_WHAT = 0x123456; private ClipDrawable mClipDrawable; private int mProgress; private PHandler handler = null; /** * 設定進度值 * @param progress 進度值0-100 */ public void setYXProgress(int progress){ auto_runing = false; handler.sendEmptyMessage(MESSAGE_WHAT); this.mProgress = (progress * 100); } /** * stop */ public void stop(){ mProgress = 0; auto_runing = false; } public YXClipProgress(Context context) { this(context,null); // TODO Auto-generated constructor stub } public YXClipProgress(Context context, AttributeSet attrs) { this(context, attrs,0); // TODO Auto-generated constructor stub } public YXClipProgress(Context context, AttributeSet set, int defStyle) { super(context, set, defStyle); // TODO Auto-generated constructor stub customInitAttribute(context,set,0); initThread(context); } private void initThread(Context context) { // TODO Auto-generated method stub new Thread(new Runnable() { @Override public void run() { while(auto_runing){ handler.sendEmptyMessage(MESSAGE_WHAT); if(mProgress>MAX_PROGRESS){ mProgress = 0; } mProgress += 100; try { Thread.sleep(50); } catch (Exception e) { e.printStackTrace(); } } } }).start(); } private void customInitAttribute(Context context, AttributeSet set, int defStyle) { /*開啟Handler*/ handler = new PHandler(this); /* 配置屬性值 */ TypedArray a = context.obtainStyledAttributes(set,R.styleable.YXClipProgress); auto_runing = a.getBoolean(R.styleable.YXClipProgress_autoRuning, false); mProgress = a.getInt(R.styleable.YXClipProgress_progress, 0) * 100; a.recycle(); /* inflate */ View view = LayoutInflater.from(context).inflate(R.layout.yx_clipprogress_layout, null); addView(view); ImageView imageView = (ImageView) findViewById(R.id.iv_progress); mClipDrawable = (ClipDrawable) imageView.getDrawable(); mClipDrawable.setLevel(mProgress); } private static class PHandler extends Handler{ WeakReference<YXClipProgress> mp; PHandler(YXClipProgress a){ mp = new WeakReference<YXClipProgress>(a); } @Override public void handleMessage(Message msg) { YXClipProgress t = mp.get(); if(msg.what == MESSAGE_WHAT){ t.mClipDrawable.setLevel(t.mProgress); } } } }