|
这次主要跟大家说说,如何实现一个自定义的进度条。希望可以通过本次实现,让大家了解一下,如何在Android 上实现自定义控件的。在讲解之前,先说说在A ndroid上实现自定义控件的大概方法。概括如下: 1、
自定义的单个控件分别是重新继承View 或者其子类和SurfaceView 或者其子类。如果是一般的应用程序开始,继承View 或者其子类就可以了,我们需要做的,就是重写onDraw(canver) 。SuerfaceView 主要用于帧数要求比较高的应用,如“视频播放”和游戏开发,尤其是3D 游戏开发,这里不详细叙述,以后说到关于游戏开发,我会专以一个帖子讲解的。 2、
自定义的组合控件组合的控件,因名思议,就是把几个控件组合在一起,组合成一个更大的控件。一般是继承一个Layout ,如ReleativeLayout 、LinearLayout 、TableLayout 等等,视具体情况而定。当然,装在Layout 里而子控件,可以是系统自带的,也可以通过第一方式自定义的控件。这样,只要大家发挥想象,通过上面两种方法,就可以组合出千变万化的控件了,一句话“没有做不到,只有想不到”。 一、原理说完 ,下面先上图,让大家看看最终效果吧,如下图:
图一
图一
二、要求:
要求进度条能从左到右减少。系统自带的进度条,好像没有方向可以设置的(有知道如何设置童鞋,希望说一下,谢谢~)。
三、技术点和难点
主要的技术点:Android的Handle机制,ReleativeLayout的相对布局。 主要的难点:在Android上,是不可以动态修改view的layout_width和layout_height的,因此要动态修改进度条的长度,需要不断“删除—增加”ImageView的方式来实现,而每次add进parent的ImageView的layout_width需要根据当前parent的width、max_value、current_progress三者计算出来,长度
= parent_width *
(current_progress/max_value);另外还有一点,非常重要的,就是每次更换ImageView时,都必须交生成一个线程,post给handle来做,这里才不会造成界面阻塞,这一点很重要,不然界面要卡死的!!
图三四、代码
本帖隐藏的内容需要回复才可以浏览
01 |
public class MobileTokenProcessBar
extends RelativeLayout { |
02 |
private int m_max = 20;
|
03 |
private int m_process =
0;
|
04 |
private ImageView mImageView = null;
|
05 |
private LayoutParams params; |
06 |
private Handler mHandler; |
07 |
private Thread mThread = new
Thread(new
Runnable() { |
10 |
reflashPorcess(m_process); |
14 |
public MobileTokenProcessBar(Context context, AttributeSet attrs) {
|
15 |
super(context, attrs); |
19 |
public MobileTokenProcessBar(Context context){
|
25 |
setBackgroundResource(R.drawable.processbar_out_bg);
|
26 |
mHandler = new Handler(getContext().getMainLooper());
|
27 |
params = new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT); |
28 |
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
|
31 |
public void setMax(int max){
|
39 |
public void setProgress(int
process){ |
40 |
if(process <= m_max ){
|
42 |
mHandler.post(mThread);
|
46 |
public int getProgress(){
|
50 |
private int getCountLength(){
|
51 |
return (getWidth() - 16) * m_process / m_max;
|
54 |
private void reflashPorcess(int
process){ |
55 |
if(mImageView != null)
|
56 |
removeView(mImageView);
|
58 |
mImageView = new ImageView(getContext());
|
59 |
mImageView.setAdjustViewBounds(true);
|
60 |
mImageView.setScaleType(ScaleType.FIT_XY);
|
61 |
mImageView.setImageResource(R.drawable.processbar_in_bg);
|
62 |
params.width = getCountLength();
|
63 |
addView(mImageView, params);
|
百度新闻源正式收录mmclick.com,欢迎投稿,稿件一经审核通过,第一时间在本网进行发布。
投稿信箱 media@mmclick.com。
|