android 如何自定义ProgressBar

原文:http://blog.sina.com.cn/s/blog_74c22b210100thpv.html

1. 在res/values/colors.xml中定义ProgressBar要用的图片颜色

<?xml version="1.0" encoding="utf-8"?>
<resources>
        <!--定义图片颜色-->
<drawable name="transparent_background">#00000000</drawable>
<drawable name="white">#ffffff</drawable>

         <!--定义文字颜色-->
< color  name ="solid_red" > #f00 </ color >
<color name="solid_blue">#0000ff</color>
</resources>

2. res/drawable/progress_bar_layer.xml中自定义ProgressBar进度条的颜色以及背景
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@android:id/background" 
      android:drawable="@drawable/transparent_background" />

<item android:id="@android:id/progress">
<clip>
<shape>
   <gradient android:startColor="#FFFFD980" android:centerColor="#FFFF8C00"         android:endColor="#FF6611" android:angle="270" android:centerY="0.75" />
</shape>
</clip>
</item>
</layer-list>


android:angle 0 is left to right, 90 is bottom to top, 180 is right to left, 270 is top to bottom
android:centerY 自上而下(androidL:angle="270")从3/4处开始颜色渐变(默认在1/2处)

3.在res/layout/main.xml定义ProgressBar在应用中的布局表示
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="wrap_content">
<ProgressBar android:layout_width="fill_parent"
     android:layout_height="148dp" android:id="@+id/my_profile_tracker"
     android:background="@null" 
     android:progressDrawable="@drawable/progress_bar_layer"
     android:paddingLeft="23dp" android:paddingRight="23dp"
     android:paddingTop="107dp" android:paddingBottom="27dp"
     style="?android:attr/progressBarStyleHorizontal"
     android:indeterminateOnly="false" android:max="60" />
<ImageView android:id="@+id/my_profile_tracker_mask" 
android:layout_width="fill_parent"
android:layout_height="148dp" 
android:src="@drawable/profile_screen_tracker" />
</RelativeLayout>

style="?android:attr/progressBarStyleHorizontal" 定义ProgressBar为水平类型
android:progressDrawable="@drawable/progress_bar_layer" Drawable used for the progress mode. 


4. 至此关于ProgressBar在xml中的定义全部完成了,你需要做的就是在java文件中引用他们
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ProgressBar mTracker = (ProgressBar) findViewById(R.id.my_profile_tracker);
mTracker.setProgress(20);
}

对于上面的 <clip>  元素,
如果设置mTracker.setProgress(0);那么你将不会看到ProgressBar
如果设置mTracker.setProgress(20);那么你将可以看到ProgressBar

官方文档对于<clip>元素的解释

The default level is 0, which is fully clipped so the image is not visible. When the level is 10,000, the image is not clipped and completely visible.

正如你所看到的,当level为0,全部裁剪不可见,即为以下样式( setProgress(0)
android <wbr>如何自定义ProgressBar


setProgress(20)则才会出现ProgressBar.

android <wbr>如何自定义ProgressBar

你可能感兴趣的:(ProgressBar)