在开发中总会需要自定义各种View的样式,如果总是依赖美工作图弄出需要的UI样式图片(比如:一个按钮要选中和默认两张图片),不但时间上会浪费、往往也会有适配问题。虽然可以通过.9图来解决一些适配问题,依然要花不少时间,毕竟美工通常不懂.9图的制作(得自己动手)。所以有时可以通过简单的创建android XML的方式制作需要的View的UI样式(不但快捷,更不会有适配问题)。
以下XML代码创建了一个4dip圆角带2px边框的样式(
start_use_btn_selector.xml
)。(带有点击、选中、默认三总状态)
<?
xml
version
=
"1.0"
encoding
=
"utf-8"
?>
< selector xmlns:android = "http://schemas.android.com/apk/res/android" >
< item android:state_selected = "true" > <!-- 选中状态 -->
< shape android:shape = "rectangle" > <!-- 图形形状 rectangle为矩形、oval为椭圆、line为线、ring为环形 -->
< corners android:radius = "4dip" /> <!-- 四周圆角,也可以单独设置某一个角为圆角 如:设置topLeftRadius -->
< solid android:color = "#33ffffff" /> <!-- 中心填充色 -->
< stroke android:width = "2.0px" android:color = "#ffffffff" /> <!-- 边框线宽度和颜色设置 -->
</ shape >
</ item >
< item android:state_pressed = "true" > <!-- 点击状态 -->
< shape android:shape = "rectangle" >
< corners android:radius = "4dip" />
< solid android:color = "#33ffffff" />
< stroke android:width = "2.0px" android:color = "#ffffffff" />
</ shape >
</ item >
< item > <!-- 默认状态 -->
< shape android:shape = "rectangle" >
< corners android:radius = "4dip" />
< solid android:color = "#00ffffff" />
< stroke android:width = "2.0px" android:color = "#ffffffff" />
</ shape >
</ item >
</ selector >
< selector xmlns:android = "http://schemas.android.com/apk/res/android" >
< item android:state_selected = "true" > <!-- 选中状态 -->
< shape android:shape = "rectangle" > <!-- 图形形状 rectangle为矩形、oval为椭圆、line为线、ring为环形 -->
< corners android:radius = "4dip" /> <!-- 四周圆角,也可以单独设置某一个角为圆角 如:设置topLeftRadius -->
< solid android:color = "#33ffffff" /> <!-- 中心填充色 -->
< stroke android:width = "2.0px" android:color = "#ffffffff" /> <!-- 边框线宽度和颜色设置 -->
</ shape >
</ item >
< item android:state_pressed = "true" > <!-- 点击状态 -->
< shape android:shape = "rectangle" >
< corners android:radius = "4dip" />
< solid android:color = "#33ffffff" />
< stroke android:width = "2.0px" android:color = "#ffffffff" />
</ shape >
</ item >
< item > <!-- 默认状态 -->
< shape android:shape = "rectangle" >
< corners android:radius = "4dip" />
< solid android:color = "#00ffffff" />
< stroke android:width = "2.0px" android:color = "#ffffffff" />
</ shape >
</ item >
</ selector >
在layout中使用
<
Button
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:background="@drawable/start_use_btn_selector"
android:includeFontPadding = "false"
android:paddingBottom = "2dip"
android:paddingLeft = "28dip"
android:paddingRight = "28dip"
android:paddingTop = "2dip"
android:text = "马上体验"
android:textColor = "#FFFFFFFF"
android:textSize = "20sp" />
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:background="@drawable/start_use_btn_selector"
android:includeFontPadding = "false"
android:paddingBottom = "2dip"
android:paddingLeft = "28dip"
android:paddingRight = "28dip"
android:paddingTop = "2dip"
android:text = "马上体验"
android:textColor = "#FFFFFFFF"
android:textSize = "20sp" />
效果图(背景绿色是整体layout颜色)