本文实例讲述了Android开发中自定义ProgressBar控件的方法。分享给大家供大家参考,具体如下:
很简单,首先加载Drawable,在onMeasure设置好其区域大小,
然后使用canvas.clipRect绘图
public class ProgressView extends ImageView { private Drawable maskDraw; /** * 加载的进度 0-100 */ 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 剪切出一个区域,使在这个区域里面的内容是有效的,区域之外是无效的。 */ 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相关内容感兴趣的读者可查看本站专题:《Android窗口相关操作技巧总结》、《Android开发入门与进阶教程》、《Android调试技巧与常见问题解决方法汇总》、《Android基本组件用法总结》、《Android视图View技巧总结》、《Android布局layout技巧总结》及《Android控件用法总结》
希望本文所述对大家Android程序设计有所帮助。