Android ProgressBar详解以及自定义

来源:互联网 发布:英语口语测试软件 编辑:程序博客网 时间:2024/05/19 13:27

转载网址:http://www.2cto.com/kf/201405/301568.html

这一次主要说一下Android下的进度条,为什么是它呢,因为近期被其各种美轮美奂的设计所倾倒,计划逐渐去实现。另外一个因素也是它也是为数不多的直接继承于View类的控件,从中 是不是很漂亮,其实就像上面图形展示的那样,进度条大体上无非就是这几种形式。这样一来肯定是需要自定义了,所以方向有两个:要么继承于系统的ProgressBar;要么继承于View类(前者就是如此实现)。那就先看一下系统的进度条吧。

android.widget

Class ProgressBar

  • java.lang.Object
    • android.view.View
      • android.widget.ProgressBar
  • All Implemented Interfaces:
    Drawable.Callback,AccessibilityEventSource,KeyEvent.Callback
    Direct Known Subclasses:
    AbsSeekBar

    继承于View类,直接子类有AbsSeekBar和ContentLoadingProgressBar,其中AbsSeekBar的子类有SeekBar和RatingBar,可见这二者也是基于ProgressBar实现的。对于ProgressBar的使用,有三个地方需要注意一下: 1、ProgressBar有两个进度,一个是android:progress,另一个是android:secondaryProgress。后者主要是为缓存需要所涉及的,比如在看网络视频时候都会有一个缓存的进度条以及还要一个播放的进度,在这里缓存的进度就可以是android:secondaryProgress,而播放进度就是android:progress。 2、ProgressBar分为确定的和不确定的,上面说的播放进度、缓存等就是确定的。相反地,不确定的就是不清楚、不确定一个操作需要多长时间来完成,这个时候就需要用的不确定的ProgressBar了。这个是由属性android:indeterminate来控制的,如果设置为true的话,那么ProgressBar就可能是圆形的滚动条或者水平的滚动条(由样式决定)。默认情况下,如果是水平进度条,那么就是确定的。 3、ProgressBar的样式设定其实有两种方式,在API文档中说明的方式如下:
      Widget.ProgressBar.HorizontalWidget.ProgressBar.SmallWidget.ProgressBar.LargeWidget.ProgressBar.InverseWidget.ProgressBar.Small.InverseWidget.ProgressBar.Large.Inverse 使用的时候可以这样:style="@android:style/Widget.ProgressBar.Small"。另外还有一种方式就是使用系统的attr,上面的方式是系统的style:
        style="?android:attr/progressBarStyle" style="?android:attr/progressBarStyleHorizontal" style="?android:attr/progressBarStyleInverse" style="?android:attr/progressBarStyleLarge" style="?android:attr/progressBarStyleLargeInverse" style="?android:attr/progressBarStyleSmall" style="?android:attr/progressBarStyleSmallInverse" style="?android:attr/progressBarStyleSmallTitle" 然后再看一下ProgressBar的其他常用属性,
          关于这些属性的使用还是比较简单,不多做介绍。其中第一个android:animationResolution已经呗舍弃了,所以不要去研究它了。重点说一下android:progressDrawable以及android:indeterminateDrawable。那这个Drawable在ProgressBar中是如何使用的呢,如果我们是这样在xml中设置ProgressBar的话,
          <progressbar android:id="@+id/progressbar"style="@android:style/Widget.ProgressBar.Horizontal"android:layout_width="match_parent"android:layout_height="wrap_content"android:secondaryprogress="50"></progressbar>
            虽然没有设置android:indeterminateDrawable,但是样式Widget.ProgressBar.Horizontal已经帮我们设置好了。查看源码如下:
          <style name="Widget.ProgressBar.Horizontal">
              <item name="android:indeterminateOnly">false</item>
              <item name="android:progressDrawable">@android:drawable/progress_horizontal</item>
              <item name="android:indeterminateDrawable">@android:drawable/progress_indeterminate_horizontal</item>
              <item name="android:minHeight">20dip</item>
              <item name="android:maxHeight">20dip</item>
              <item name="android:mirrorForRtl">true</item>
          </style>
            先看一下progress_horizontal,源码如下:
          <!--?xml version="1.0"encoding="utf-8"?-->
          <!-- Copyright (C) 2008The Android Open Source Project
           
               Licensed under the Apache License, Version 2.0(the "License");
               you may not use thisfile except in compliance with the License.
               You may obtain a copy of the License at
           
                    http://www.apache.org/licenses/LICENSE-2.0
           
               Unless required by applicable law or agreed to in writing, software
               distributed under the License is distributed on an "AS IS" BASIS,
               WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
               See the License forthe specific language governing permissions and
               limitations under the License.
          -->
           
          <layer-list xmlns:android="http://schemas.android.com/apk/res/android">
              
              <item android:id="@android:id/background">
                  <shape>
                      <corners android:radius="5dip">
                      <gradient android:startcolor="#ff9d9e9d"android:centercolor="#ff5a5d5a"android:centery="0.75"android:endcolor="#ff747674"android:angle="270">
                  </gradient></corners></shape>
              </item>
              
              <item android:id="@android:id/secondaryProgress">
                  <clip>
                      <shape>
                          <corners android:radius="5dip">
                          <gradient android:startcolor="#80ffd300"android:centercolor="#80ffb600"android:centery="0.75"android:endcolor="#a0ffcb00"android:angle="270">
                      </gradient></corners></shape>
                  </clip>
              </item>
              
              <item android:id="@android:id/progress">
                  <clip>
                      <shape>
                          <corners android:radius="5dip">
                          <gradient android:startcolor="#ffffd300"android:centercolor="#ffffb600"android:centery="0.75"android:endcolor="#ffffcb00"android:angle="270">
                      </gradient></corners></shape>
                  </clip>
              </item>
              
          </layer-list>
            可以看到,系统使用的是图层方式,以覆盖的方式进行的。所以如果需要其他的样式的话,改变系统默认的值即可,或者参考一下系统自带的样式设置就行了。
            紧接着,说一下ProgressBar的方法,总体来说,可以分为两个部分。一是和自身属性相关的,比如获取进度、设置进度的最大值、设置插入器等等。二是和绘制相关的部分,如图所示:

            所以、所以我们本次最重要的部分来了,那就是如何自定义一个漂亮ProgressBar。在自定义之前,先看一下系统是如何实现的。Android下ProgressBar的代码量不算多,除去注释估计也就是几百行左右。首先从构造方法看是看,
          progress bar with range 0...100 and initial progress of 0.
             * @param context the application environment
             */
            publicProgressBar(Context context) {
                this(context,null);
            }
            
            publicProgressBar(Context context, AttributeSet attrs) {
                this(context, attrs, com.android.internal.R.attr.progressBarStyle);
            }
           
            publicProgressBar(Context context, AttributeSet attrs, intdefStyle) {
                this(context, attrs, defStyle, 0);
            }
           
            /**
             * @hide
             */
            publicProgressBar(Context context, AttributeSet attrs, intdefStyle, intstyleRes) {
                super(context, attrs, defStyle);
                mUiThreadId = Thread.currentThread().getId();
                initProgressBar();
           
                TypedArray a =
                    context.obtainStyledAttributes(attrs, R.styleable.ProgressBar, defStyle, styleRes);
                
                mNoInvalidate = true;
                
                Drawable drawable = a.getDrawable(R.styleable.ProgressBar_progressDrawable);
                if(drawable != null) {
                    drawable = tileify(drawable, false);
                    // Calling this method can set mMaxHeight, make sure the corresponding
                    // XML attribute for mMaxHeight is read after calling this method
                    setProgressDrawable(drawable);
                }
           
           
                mDuration = a.getInt(R.styleable.ProgressBar_indeterminateDuration, mDuration);
           
                mMinWidth = a.getDimensionPixelSize(R.styleable.ProgressBar_minWidth, mMinWidth);
                mMaxWidth = a.getDimensionPixelSize(R.styleable.ProgressBar_maxWidth, mMaxWidth);
                mMinHeight = a.getDimensionPixelSize(R.styleable.ProgressBar_minHeight, mMinHeight);
                mMaxHeight = a.getDimensionPixelSize(R.styleable.ProgressBar_maxHeight, mMaxHeight);
           
                mBehavior = a.getInt(R.styleable.ProgressBar_indeterminateBehavior, mBehavior);
           
                finalint resID = a.getResourceId(
                        com.android.internal.R.styleable.ProgressBar_interpolator,
                        android.R.anim. linear_interpolator); // default to linear interpolator
                if(resID > 0) {
                    setInterpolator(context, resID);
                }
           
                setMax(a.getInt(R.styleable.ProgressBar_max, mMax));
           
                setProgress(a.getInt(R.styleable.ProgressBar_progress, mProgress));
           
                setSecondaryProgress(
                        a.getInt(R.styleable.ProgressBar_secondaryProgress, mSecondaryProgress));
           
                drawable = a.getDrawable(R.styleable.ProgressBar_indeterminateDrawable);
                if(drawable != null) {
                    drawable = tileifyIndeterminate(drawable);
                    setIndeterminateDrawable(drawable);
                }
           
                mOnlyIndeterminate = a.getBoolean(
                        R.styleable.ProgressBar_indeterminateOnly, mOnlyIndeterminate);
           
                mNoInvalidate = false;
           
                setIndeterminate( mOnlyIndeterminate || a.getBoolean(
                        R.styleable.ProgressBar_indeterminate, mIndeterminate));
           
                mMirrorForRtl = a.getBoolean(R.styleable.ProgressBar_mirrorForRtl, mMirrorForRtl);
            样式文件如下:
          R.styleable.Progre:
           <declare-styleable name="ProgressBar">
                  <!-- Defines the maximum value the progress can take. -->
                   
                  <!-- Defines the defaultprogress value, between 0and max. -->
                   
                  <!-- Defines the secondary progress value, between 0and max. This progress is drawn between
                       the primary progress and the background.  It can be ideal formedia scenarios such as
                       showing the buffering progress whilethe defaultprogress shows the play progress. -->
                   
                  <!-- Allows to enable the indeterminate mode. In thismode the progress
                   bar plays an infinite looping animation. -->
                   
                  <!-- Restricts to ONLY indeterminate mode (state-keeping progress mode will not work). -->
                   
                  <!-- Drawable used forthe indeterminate mode. -->
                   
                  <!-- Drawable used forthe progress mode. -->
                   
                  <!-- Duration of the indeterminate animation. -->
                   
                  <!-- Defines how the indeterminate mode should behave when the progress
                  reaches max. -->
                   
                      <!-- Progress starts over from 0. -->
                      <enumname="repeat"value="1">
                      <!-- Progress keeps the current value and goes back to 0. -->
                      <enumname="cycle"value="2">
                  </enum></enum></attr>
                   
                   
                   
                   
                   
                  <!-- Timeout between frames of animation in milliseconds
                       {@deprecatedNot used by the framework.} -->
                   
              </attr></attr></attr></attr></attr></attr></attr></attr></attr></attr></attr></attr></attr></attr></declare-styleable>

      ProgressBar把三个构造方法都列出来了,并使用了递归调用的方式,还有一个方式就是分别在每一个构造方法中都调用初始化的代码,个人觉得还是此处比较正规。然后看一下第三个构造方法,在这里主要做了两件事情,一个是从attrs文件中读取设置的属性;一个是initProgressBar()方法,为ProgressBar设置一些默认的属性值。
    privatevoid initProgressBar() {
          mMax = 100;
          mProgress = 0;
          mSecondaryProgress = 0;
          mIndeterminate = false;
          mOnlyIndeterminate = false;
          mDuration = 4000;
          mBehavior = AlphaAnimation.RESTART;
          mMinWidth = 24;
          mMaxWidth = 48;
          mMinHeight = 24;
          mMaxHeight = 48;
      }
      这就是默认的属性值。这在自定义View中算是最基础的了,不多说,不过在这里需要注意两个地方。一是mUiThreadId,他是干嘛的呢,它获取的是当前UI线程的id,然后在更新ProgressBar进度的时候进行一个判断,如果是UI线程,那么直接进行更新,如果不是就post出去,使用Handler等进行更新。二是tileify(drawable, false)方法和tileifyIndeterminate(drawable)方法。这两个方法主要是对Drawable进行一个解析、转换的过程。在这里需要重点强调一下,在ProgressBar中,最重要的部分就是Drawable的使用了,因为不仅是它的背景包括进度等都是使用Drawable来完成的,所以在源码中也可以看到基本上百分之七八十的代码都是和Drawable有关的。因为这一部分篇幅较多,所以就不详细介绍了,下面重点说一下如何绘制ProgressBar,首先看onMeasure()方法,
    @Override
       protectedsynchronized void onMeasure( intwidthMeasureSpec, intheightMeasureSpec) {
           Drawable d = mCurrentDrawable;
     
           intdw = 0;
           intdh = 0;
           if(d != null) {
               dw = Math. max(mMinWidth , Math.min( mMaxWidth, d.getIntrinsicWidth()));
               dh = Math. max(mMinHeight , Math.min( mMaxHeight, d.getIntrinsicHeight()));
           }
           updateDrawableState();
           dw += mPaddingLeft + mPaddingRight;
           dh += mPaddingTop + mPaddingBottom;
     
           setMeasuredDimension( resolveSizeAndState(dw, widthMeasureSpec, 0),
                   resolveSizeAndState(dh, heightMeasureSpec, 0));
       }

    这是测量View大小的方法,也就是ProgressBar的大小,因为每一个ProgressBar默认都会使用Drawable。所以ProgressBar的大小即是Drawable的大小加上Padding的大小,如果没有Padding,那很显然就是Drawable的大小。最后使用setMeasuredDimension()方法设置ProgressBar的大小。 按照正常的流程,有些朋友可能会想到重写onLayout()方法了,但是这里ProgressBar只是一个View,不需要进行位置的处理。所以直接进入onDraw()方法,在
@Override
   protectedsynchronized void onDraw(Canvas canvas) {
       super.onDraw(canvas);
 
       Drawable d = mCurrentDrawable;
       if(d != null) {
           // Translate canvas so a indeterminate circular progress bar with padding
           // rotates properly in its animation
           canvas.save();
           if(isLayoutRtl() && mMirrorForRtl) {
               canvas.translate(getWidth() - mPaddingRight, mPaddingTop);
               canvas.scale(-1.0f,1.0f);
           }else{
               canvas.translate(mPaddingLeft, mPaddingTop);
           }
           longtime = getDrawingTime();
           if( mHasAnimation) {
               mAnimation.getTransformation(time, mTransformation);
               floatscale = mTransformation.getAlpha();
               try{
                   mInDrawing = true;
                   d.setLevel((int) (scale * MAX_LEVEL));
               }finally{
                   mInDrawing = false;
               }
               postInvalidateOnAnimation();
           }
           d.draw(canvas);
           canvas.restore();
           if( mShouldStartAnimationDrawable && d instanceofAnimatable) {
               ((Animatable) d).start();
               mShouldStartAnimationDrawable = false;
           }
       }
    首先也是先获取当前的Drawable对象,如果不为空就开始绘图,先是一个判断,根据布局的方向来转移画布,isLayoutRtl()是View类的方法,
publicboolean isLayoutRtl() {
      return(getLayoutDirection() == LAYOUT_DIRECTION_RTL);
  }
    这个LAYOUT_DIRECTION_RTL是LayoutDirection的一个常量,
packageandroid.util;
 
/**
* A class for defining layout directions. A layout direction can be left-to-right (LTR)
* or right-to-left (RTL). It can also be inherited (from a parent) or deduced from the default
* language script of a locale.
*/
publicfinal class LayoutDirection {
 
    // No instantiation
    privateLayoutDirection() {}
 
    /**
     * Horizontal layout direction is from Left to Right.
     */
    publicstatic final int LTR = 0;
 
    /**
     * Horizontal layout direction is from Right to Left.
     */
    publicstatic final int RTL = 1;
 
    /**
     * Horizontal layout direction is inherited.
     */
    publicstatic final int INHERIT = 2;
 
    /**
     * Horizontal layout direction is deduced from the default language script for the locale.
     */
    publicstatic final int LOCALE = 3;
}
    然后再判断有没有动画,如果有的话,就调用View类的postInvalidateOnAnimation()方法去执行一个动画。最后调用Drawable对象去画出来d.draw(canvas)。 总的来说,系统的ProgressBar是和Drawable紧密相关的,所以说,如果我们自定义的ProgressBar和Drawable有关,那么完全可以继承于系统的ProgressBar来开发即可。如果你的自定义ProgressBar和Drawable关系不大
    不需要Drawable了,完全可以直接继承于View类开发。

0 0
原创粉丝点击