首页 > 代码库 > android shape图形优化Button效果

android shape图形优化Button效果

  android shape可以让我们通过定义xml文件的方式创建图形,当然只能实现一些比较简单的图形(圆形,矩形,椭圆,线段),但是已经相当不错了,通过shape创建的图形作为控件的背景已经基本可以满足我的简单需求了,而且通过shape创建的图形可以适配各种屏幕。

  下面就用shape定义的图形来优化Button的整体效果。

  定义主布局文件activity_main.xml:

 1 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 2     xmlns:tools="http://schemas.android.com/tools" 3     android:layout_width="match_parent" 4     android:layout_height="match_parent" 5     tools:context=".MainActivity" > 6  7     <Button  8         android:layout_height="48dp" 9         android:layout_width="160dp"10         android:background="@drawable/button_selector"11         android:layout_centerInParent="true"12         android:text="按钮"/>13 </RelativeLayout>

   定义Button的状态选择器button_selector.xml:

1 <?xml version="1.0" encoding="utf-8"?>2 <selector3   xmlns:android="http://schemas.android.com/apk/res/android">4     <item android:state_focused="false" android:state_selected="true" android:state_pressed="false" android:drawable="@drawable/button_shape" />5     <item android:state_focused="false" android:state_selected="false" android:state_pressed="false" android:drawable="@drawable/button_shape" />6     <item android:state_pressed="true" android:drawable="@drawable/button_shape_press" />7     <item android:state_focused="true" android:state_selected="true" android:state_pressed="false" android:drawable="@drawable/button_shape" />8 </selector>

  定义Button未点击状态的背景button_shape.xml:

 1 <?xml version="1.0" encoding="UTF-8" standalone="no"?> 2 <shape xmlns:android="http://schemas.android.com/apk/res/android" 3     android:shape="rectangle"> 4     <!--渐变 --> 5     <gradient android:angle="0" android:endColor="#DCDCE1" android:startColor="#DCDCE1" android:centerColor="#DCDCE1"/> 6     <!--实心  --> 7     <solid android:color="#DCDCE1"/> 8     <!--圆角,可定义四个圆角的大小  --> 9     <corners android:radius="3dp" />10     <!--描边, 可设置边的宽度颜色 -->11     <stroke android:width="1dp" android:color="#C8C8CD" />12     <!--内边距-->13     <padding android:bottom="0dp" android:left="0dp" android:right="0dp" android:top="0dp"/>14 </shape>

  定义Button点击状态的背景button_shape_press.xml:

1 <?xml version="1.0" encoding="UTF-8" standalone="no"?>2 <shape xmlns:android="http://schemas.android.com/apk/res/android"3     android:shape="rectangle">4     <gradient android:angle="0" android:endColor="#C8C8CD" android:startColor="#C8C8CD" android:centerColor="#C8C8CD"/>5     <solid android:color="#C8C8CD"/>6     <corners android:radius="3dp"/>7     <stroke android:width="1dp" android:color="#C8C8CD" />8     <padding android:bottom="0dp" android:left="0dp" android:right="0dp" android:top="0dp"/>9 </shape>

 

最终效果如下图: