在实际的工作中经常需要根据美工的设计来改变一些控件的颜色,式样,以及背景图片,下面和大家共同探讨一下在Android中如何自定义SeekBar的背景颜色,进度条的颜色,以及滑块的图片
首先在layout文件夹中的main.xml内容如下
1. <?xml version="1.0" encoding="utf-8"?> 2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3. android:orientation="vertical" android:layout_width="fill_parent" 4. android:layout_height="fill_parent"> 5. 6. <SeekBar android:id="@+id/seek" android:layout_width="300px" 7. android:layout_height="wrap_content" android:max="100" 8. android:progress="50" android:progressDrawable="@drawable/seekbar_img" 9. android:thumb="@drawable/thumb" /> 10. </LinearLayout>
注意它的 android:progressDrawable="@drawable/seekbar_img" 以及 android:thumb="@drawable/thumb" 它们分别对应的是 进度条的图片以及拖动滑块的图片,这里的图片也可以是我们自定义的drawable中的xml文件,可以理解成这两个属性应该如何显示的意思,而 @drawable/seekbar_img和@drawable/thumb它们分别对应着 drawable 文件夹中的文件seekbar_img.xml和thumb.xml,它们表示着如何去显示进度条与滑块
系统中自带的seek_thumb.xml,内容如下
1. <?xml version="1.0" encoding="utf-8"?> 2. <!-- Copyright (C) 2008 The Android Open Source Project 3. 4. Licensed under the Apache License, Version 2.0 (the "License"); 5. you may not use this file except in compliance with the License. 6. You may obtain a copy of the License at 7. 8. http://www.apache.org/licenses/LICENSE-2.0 9. 10. Unless required by applicable law or agreed to in writing, software 11. distributed under the License is distributed on an "AS IS" BASIS, 12. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13. See the License for the specific language governing permissions and 14. limitations under the License. 15. --> 16. 17. <!-- This is the thumb on the seek bar. --> 18. <selector xmlns:android="http://schemas.android.com/apk/res/android"> 19. 20. <item android:state_pressed="true" 21. android:state_window_focused="true" 22. android:drawable="@drawable/seek_thumb_pressed" /> 23. 24. <item android:state_focused="true" 25. android:state_window_focused="true" 26. android:drawable="@drawable/seek_thumb_selected" /> 27. 28. <item android:state_selected="true" 29. android:state_window_focused="true" 30. android:drawable="@drawable/seek_thumb_selected" /> 31. 32. <item android:drawable="@drawable/seek_thumb_normal" /> 33. 34. </selector>
1. <?xml version="1.0" encoding="utf-8"?> 2. <layer-list xmlns:android="http://schemas.android.com/apk/res/android"> 3. <!-- 背景图 --> 4. <item android:id="@+android:id/background" android:drawable="@drawable/bg" /> 5. <!--全部能量图 --> 6. <item android:id="@+android:id/SecondaryProgress" 7. android:drawable="@drawable/bg" /> 8. <!-- 进和能量图 --> 9. <item android:id="@+android:id/progress" android:drawable="@drawable/bg2" /> 10. </layer-list>thumb.xml