三、技术点和难点
主要的技术点: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来做,这里才不会造成界面阻塞,这一点很重要,不然界面要卡死的!
java代码:
public class MobileTokenProcessBar extends RelativeLayout {private int m_max = 20;private int m_process = 0;private ImageView mImageView = null;private LayoutParams params;private Handler mHandler;private Thread mThread = new Thread(new Runnable() {@Overridepublic void run() {reflashPorcess(m_process);//界面的修改,交由线程来处理}});public MobileTokenProcessBar(Context context, AttributeSet attrs) {super(context, attrs);init();}public MobileTokenProcessBar(Context context){super(context);init();}private void init(){setBackgroundResource(R.drawable.processbar_out_bg);mHandler = new Handler(getContext().getMainLooper());params = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);}public void setMax(int max){m_max = max;}public int getMax(){return m_max;}public void setProgress(int process){if(process <= m_max ){m_process = process;mHandler.post(mThread);}}public int getProgress(){return m_process;}private int getCountLength(){return (getWidth() - 16) * m_process / m_max;}private void reflashPorcess(int process){if(mImageView != null)removeView(mImageView);mImageView = null;mImageView = new ImageView(getContext());mImageView.setAdjustViewBounds(true);mImageView.setScaleType(ScaleType.FIT_XY);mImageView.setImageResource(R.drawable.processbar_in_bg);params.width = getCountLength();addView(mImageView, params);}}