首页 > 代码库 > 自定义Button成进度条
自定义Button成进度条
ProgressButton源码:
package com.example.progressbutton; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.widget.Button; /** * @author Administrator * @time 2015-7-19 下午4:41:06 * @des TODO * * @version $Rev$ * @updateAuthor $Author$ * @updateDate $Date$ * @updateDes TODO */ public class ProgressButton extends Button { private boolean mProgressEnable; private long mMax = 100; private long mProgress; private Drawable mProgressDrawable; /**设置是否允许进度*/ public void setProgressEnable(boolean progressEnable) { mProgressEnable = progressEnable; } /**设置进度的最大值*/ public void setMax(long max) { mMax = max; } /**设置当前的进度,并且进行重绘操作*/ public void setProgress(long progress) { mProgress = progress; invalidate(); } /**设置progressButton的进度图片*/ public void setProgressDrawable(Drawable progressDrawable) { mProgressDrawable = progressDrawable; } public ProgressButton(Context context, AttributeSet attrs) { super(context, attrs); } public ProgressButton(Context context) { super(context); } @Override protected void onDraw(Canvas canvas) { if (mProgressEnable) { Drawable drawable = new ColorDrawable(Color.BLUE); int left = 0; int top = 0; int right = (int) (mProgress * 1.0f / mMax * getMeasuredWidth() + .5f); int bottom = getBottom(); drawable.setBounds(left, top, right, bottom);// 必须的.告知绘制的范围 drawable.draw(canvas); } super.onDraw(canvas);// 绘制文本,还会绘制背景 } }
控制显示Demo:
package com.example.progressbutton; import android.os.AsyncTask; import android.os.Bundle; import android.os.SystemClock; import android.app.Activity; import android.view.Menu; import android.view.View; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void click(final View view) { new AsyncTask<Void, Integer, Void>() { int progress=0; private ProgressButton mButton; @Override protected void onPreExecute() { mButton = (ProgressButton) view; mButton.setProgressEnable(true); } @Override protected Void doInBackground(Void... params) { for (int i = 0; i <= 100; i++) { SystemClock.sleep(100); publishProgress(i); } return null; } @Override protected void onProgressUpdate(Integer... values) { mButton.setProgress(values[0]); mButton.setText(values[0]+"%"); } protected void onPostExecute(Void result) { }; }.execute(); } }
效果图:
自定义Button成进度条
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。