Android自定义ProgressBar控件 Android开发中自定义ProgressBar控件的方法示例
CharlinGod 人气:0想了解Android开发中自定义ProgressBar控件的方法示例的相关内容吗,CharlinGod在本文为您仔细讲解Android自定义ProgressBar控件的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Android,自定义,ProgressBar,控件,下面大家一起来学习吧。
本文实例讲述了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程序设计有所帮助。
加载全部内容