如何使用代码更改前景和背景图片?

时间:2013-01-06 08:15:12

标签: android 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 个答案:

答案 0 :(得分:2)

XML布局明智

seekbar_progress.xml,将其放在/ res / 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">
    <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);

答案 1 :(得分:1)

layer-list xml资源实际上创建了一个LayerDrawable实例。您可以使用setDrawableByLayerId方法更改其图层,也可以使用所需的任何图层创建新的可绘制实例。