这篇文章将为大家详细讲解有关怎么在Android中自定义一个ProgressBar控件,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。
首先加载Drawable,在onMeasure设置好其区域大小,
然后使用canvas.clipRect绘图
public class ProgressView extends ImageView { private Drawable maskDraw; private int mProcess = 20; public ProgressView(Context context, AttributeSet attrs) { super(context, attrs); maskDraw = context.getResources().getDrawable(R.drawable.red_bg); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); // 保存当前画笔的状态 canvas.save(); int topline = (int) (getHeight() - getHeight() * getProcess() / 100); canvas.clipRect(0, topline, getWidth(), getHeight()); maskDraw.draw(canvas); // 恢复到之前保存的状态 canvas.restore(); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); maskDraw.setBounds(0, 0, getWidth(), getHeight()); } public float getProcess() { return mProcess; } public void setProgress(int mProcess) { if (mProcess > 100) { this.mProcess = 100; } if (mProcess < 0) { this.mProcess = 0; } this.mProcess = mProcess; invalidate(); }}
使用方法
public class ProgressActivity extends Activity { private ProgressView piv; private int pivDeep = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_progressview); piv = (ProgressView) findViewById(R.id.my_pro_iv); handler.sendEmptyMessage(2); } private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case 1: piv.setProgress(pivDeep); break; case 2: new Thread() { public void run() { while (true) { pivDeep = (pivDeep + 5) % 100; handler.sendEmptyMessage(1); try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } } }; }.start(); break; default: break; } } };}
关于怎么在Android中自定义一个ProgressBar控件就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。