2015-09-21 32 views
0

我一直在尋找自定義進度條的教程和95%的我發現是如何自定義使用顏色和漸變與圖像(基本上是一個圖像的空欄圖像或頂部的完整酒吧)。當我嘗試使用進度條圖像時,尺寸錯誤(包裝內容無法正常工作,並且截斷了一半)。自定義進度條與圖像或圖像查看與剪貼

我能夠實現一個成功的酒吧與圖像使用圖像與剪貼畫和水平設置。

SOOO,是ProgressBar與圖像用於其背景/進展皺眉,我應該使用imageview呢?

+0

我不認爲這是令人難以接受的。實際上,'ProgressBar'固有地使用可繪製的剪輯來完成動畫效果。所以,我看不出爲什麼你不應該使用它。但正如你所表明的那樣,唯一的麻煩就是視角如何度量自身。所以你將不得不重寫'onMeasure'來確保你的drawable沒有被切斷 – Abhijit

+0

謝謝,有什麼聯繫或者例子來說明怎麼實現的? – Snake

回答

1

關鍵是要確保ProgressBar帳戶爲您的自定義繪圖的尺寸。一種方法是覆蓋onMeasure。這裏是你的自定義類的onMeasure實現的草圖(比較這對ProgressBar的實現 - 你會發現微妙的變化):

@Override 
protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec){ 

    // the super's onMeasure method ignores the dimensions of the custom progress drawable 
    // if they are greater than a specified height & width (mMaxHeight & mMaxWidth). It simply uses those 
    // default dimensions for the drawable, consequently resizing them; which is not suitable for larger drawables. 
    // So, it is necessary to override this method to allow the ProgressBar to account for the drawable's original 
    // dimensions and draw the image/drawable accordingly. 
    Drawable d = getProgressDrawable(); 

    int dw = 0; 
    int dh = 0; 
    if (d != null) { 
     dw = d.getIntrinsicWidth(); 
     dh = d.getIntrinsicHeight(); 
    } 

    int[] state = getDrawableState(); 
    if(mProgressDrawable != null && mProgressDrawable.isStateful()) 
     mProgressDrawable.setState(state); 

    dw += getPaddingLeft() + getPaddingRight(); 
    dh += getPaddingTop() + getPaddingBottom(); 

    setMeasuredDimension(resolveSize(dw, widthMeasureSpec), resolveSize(dh, heightMeasureSpec)); 
} 

然後,您可以將您的空欄爲背景,自定義ProgressBar像你通常會做一個視圖 - android:background="@drawable/empty_bar"

接下來的部分是設置progressDrawable,爲你將不得不使用一個<layer-list>,因爲我們要密切配合進度條的繪製結構(default drawable)。下面是一個示例:

<?xml version="1.0" encoding="UTF-8"?> 
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" > 
    <item android:id="@android:id/background"> 
     <shape> 
     <solid android:color="#00000000"/> 
     </shape> 
    </item> 
    <item android:id="@android:id/progress"> 
     <clip 
     android:clipOrientation="vertical" 
     android:gravity="bottom" 
     android:drawable="@drawable/full_bar"> 
     </clip> 
    </item> 
</layer-list> 

最後的動畫,你可以使用一個ObjectAnimator的進度:

final ObjectAnimator animator = ObjectAnimator 
      .ofInt(progressBar, "progress", 0, 100) 
      .setDuration(2000); 
animator.start(); 
+0

非常感謝。我不必使用動畫師嗎?我只能做「setProgress」或「setSecondaryProgress」正確嗎? – Snake

+0

@Snake是的,沒錯! ObjectAnimator只是通過反射隱式地做到這一點 – Abhijit