轉自http://blog.csdn.net/luckkof
正文
本文主要介紹Drawable Resources的一種,Shape Drawable Resources的使用。其他Drawable類似
經常需要自己設置某個view的背景,比如類似新浪微博客戶端微博源內容的灰底圓角效果,這個時候我們就可以使用Shape。
1、介紹
Shape Drawable Resources是指一個XML文件,它定義了幾何形狀,包括顏色和漸變。
放在res/Drawable文件夾下,文件名即爲資源id,可以在其他layout中調用R.drawable.filename,
對應的類爲ShapeDrawable
shape包含矩形、橢圓形、行、環形。
2、使用
下面以爲一個TextView設置一個漸變色的邊框爲例進行介紹,第三部分對具體屬性含義進行介紹
2.1 定義一個漸變色的矩形shape,文件路徑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>
- <TextView
- android:background="@drawable/gradient_box"
- android:layout_height="wrap_content"
- android:layout_width="wrap_content" />
其中 android:background="@drawable/gradient_box"表示設置背景爲 gradient_box 這個drawable
或者在後臺程序中設置
- Resources res = getResources();
- Drawable shape = res. getDrawable(R.drawable.gradient_box);
- TextView tv = (TextView)findViewByID(R.id.textview);
- tv.setBackground(shape);
3、屬性介紹
xml定義如下
- <?xml version="1.0" encoding="utf-8"?>
- <shape
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:shape=["rectangle" | "oval" | "line" | "ring"] >
- <corners
- android:radius="integer"
- android:topLeftRadius="integer"
- android:topRightRadius="integer"
- android:bottomLeftRadius="integer"
- android:bottomRightRadius="integer" />
- <gradient
- android:angle="integer"
- android:centerX="integer"
- android:centerY="integer"
- android:centerColor="integer"
- android:endColor="color"
- android:gradientRadius="integer"
- android:startColor="color"
- android:type=["linear" | "radial" | "sweep"]
- android:useLevel=["true" | "false"] />
- <padding
- android:left="integer"
- android:top="integer"
- android:right="integer"
- android:bottom="integer" />
- <size
- android:width="integer"
- android:height="integer" />
- <solid
- android:color="color" />
- <stroke
- android:width="integer"
- android:color="color"
- android:dashWidth="integer"
- android:dashGap="integer" />
- </shape>
其中shape必須爲根元素,android:shape定義了形狀,默認爲矩形。
corners只對矩形有效,表示圓角的度數
gradient表示漸變色
padding表示即對內的偏移
size爲shape大小
solid爲填充色
stroke爲shape邊線的設置
以上屬性的自屬性含義見drawable-Shape,更多可以使用的屬性見GradientDrawable
.