例子:XML 檔案儲存在
res/drawable/gradient_box.xml
:
<?xml version="1.0" encoding="utf-8"?>
<shapexmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:startColor="#FFFF0000"
android:endColor="#80FF00FF"
android:angle="45"/>
<paddingandroid:left="7dp"
android:top="7dp"
android:right="7dp"
android:bottom="7dp"/>
<cornersandroid:radius="8dp"/>
</shape>
下面這個 XML 把shape應用到view:
<TextView
android:background="@drawable/gradient_box"
android:layout_height="wrap_content"
android:layout_width="wrap_content"/>
在程式代碼裡擷取shape,應用到view
Resources res =getResources();
Drawable shape = res.getDrawable(R.drawable.gradient_box);
TextView tv =(TextView)findViewByID(R.id.textview);
tv.setBackground(shape);
例子
<?xml version="1.0" encoding="utf-8"?>
<shape android:shape="rectangle" xmlns:android="http://schemas.android.com/apk/res/android">
<!-- 漸變 -->
<!-- 詳細内容 http://developer.android.com/guide/topics/resources/drawable-resource.html#Shape -->
<gradient
android:startColor="#0000ff"
android:endColor="#00bfff"
android:angle="45"
android:centerX="0.5"/>
<!-- 圓角 -->
<corners
android:radius="8dp"/>
<!-- 外邊間距 -->
<padding android:left="7dp"
android:top="7dp"
android:right="7dp"
android:bottom="7dp" />
<!-- 描邊 -->
<stroke
android:width="2dp"
android:color="#dcdcdc"
android:dashWidth="5dp"
android:dashGap="0dp" />
<!-- dashgap 表示間隔 有了間隔就成了虛線 -->
</shape>