自定义shape图形资源
需求:
制作一个textView按钮,默认背景为白色圆角矩形,点击textView背景变成黑色的圆角矩形。
通过查看API文档:
This layout XML applies the shape drawable to a View:
在drawable目录下创建白色圆角矩形xml文件和黑色xml文件。
白色圆角矩形:
黑色圆角矩形:
gradient_box_presssed.xml:
TextView背景选择器:
text_selector.xml:
在TextView属性中设置:
需求:
制作一个textView按钮,默认背景为白色圆角矩形,点击textView背景变成黑色的圆角矩形。
通过查看API文档:
app Resources -->Resource Types --> Drawable --> Shape Drawable的实例代码:
XML file saved at res/drawable/gradient_box.xml
:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:startColor="#FFFF0000"
android:endColor="#80FF00FF"
android:angle="45"/>
<padding android:left="7dp"
android:top="7dp"
android:right="7dp"
android:bottom="7dp" />
<corners android:radius="8dp" />
</shape>
This layout XML applies the shape drawable to a View:
<TextView
android:background="@drawable/gradient_box"
android:layout_height="wrap_content"
android:layout_width="wrap_content" />
在drawable目录下创建白色圆角矩形xml文件和黑色xml文件。
白色圆角矩形:
gradient_box.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="8dp" />
<solid android:color="#ffffff"/>
</shape>
黑色圆角矩形:
gradient_box_presssed.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="8dp" />
<solid android:color="#44000000"/>
</shape>
TextView背景选择器:
text_selector.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@drawable/gradient_box_pressed" android:state_pressed="true"/>
<!-- pressed -->
<item android:drawable="@drawable/gradient_box_pressed" android:state_focused="true"/>
<!-- focused -->
<item android:drawable="@drawable/gradient_box"/>
<!-- default --></selector>
在TextView属性中设置:
android:background="@drawable/text_selector"