2013-01-06 133 views
0

我在seekbar中定義了前景圖片和背景圖片。現在它可以在seekbar中很好地顯示前景和背景。如何使用代碼更改前景和背景圖片?

<?xml version="1.0" encoding="utf-8"?> 
<layer-list xmlns:android="http://schemas.android.com/apk/res/android"> 
    <!-- background picture --> 
    <item android:id="@android:id/background" 
      android:drawable="@drawable/back" />  
    <!-- energy diagram --> 
    <item android:id="@android:id/progress" 
      android:drawable="@drawable/fill" /> 
</layer-list> 

我怎麼能實現改變前景圖片和背景圖片使用Java代碼?

回答

2

XML佈局-WISE

seekbar_progress.xml,把它裏面你/ RES /繪製/文件夾:

<?xml version="1.0" encoding="utf-8"?> 
<layer-list xmlns:android="http://schemas.android.com/apk/res/android"> 
<item android:id="@android:id/background"> 
    <nine-patch 
     xmlns:android="http://schemas.android.com/apk/res/android" 
     android:src="@drawable/seekbar_background" 
     android:dither="true" 
    /> 
</item> 
<item android:id="@android:id/secondaryProgress"> 
    <clip> 
     <shape> 
      <gradient 
       android:startColor="#80028ac8" 
       android:centerColor="#80127fb1" 
       android:centerY="0.75" 
       android:endColor="#a004638f" 
       android:angle="270" 
      /> 
     </shape> 
    </clip> 
</item> 
<item 
    android:id="@android:id/progress" 
    android:drawable="@drawable/seekbar_progress_bg" 
/> 
</layer-list> 

搜索欄

<SeekBar 
    android:id="@+id/frequency_slider" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:max="20" 
    android:progress="0" 
    android:secondaryProgress="0" 
    android:progressDrawable="@drawable/seekbar_progress" 
    android:thumb="@drawable/seek_thumb" 
/> 

編程

// ------------ custom seekbar 
LayerDrawable layer = (LayerDrawable) verticalSeekBar_1.getProgressDrawable(); 

Drawable draw1 = (Drawable)layer.findDrawableByLayerId(android.R.id.progress); 
Bitmap bitmap1 = BitmapFactory.decodeResource(getApplicationContext().getResources(), R.drawable.scroll_on); 

draw1 = new ClipDrawable(new BitmapDrawable(bitmap1), Gravity.AXIS_PULL_BEFORE, ClipDrawable.HORIZONTAL); 

layer.setDrawableByLayerId(android.R.id.progress, draw1); 

Drawable draw2 = (Drawable) layer.findDrawableByLayerId(android.R.id.background); 

Bitmap bitmap2 = BitmapFactory.decodeResource(getApplicationContext().getResources(), R.drawable.scroll_off); 

draw2 = new BitmapDrawable(bitmap2); 
layer.setDrawableByLayerId(android.R.id.background, draw2); 
+0

另請參閱http://www.mokasocial.com/2011/02/create-a-custom-styled-ui-slider-這些鏈接,正確理解搜索欄,在功能的Android / –

1

layer-list xml資源實際上創建了一個LayerDrawable實例。您可以使用setDrawableByLayerId方法更改其圖層,也可以使用所需的任何圖層創建新的可繪製實例。