Android Shape Drawable Resources TextView漸變 背景色 圓角
阿新 • • 發佈:2019-02-19
正文
本文主要介紹Drawable Resources的一種,Shape Drawable Resources的使用。其他Drawable類似
經常需要自己設定某個view的背景,比如類似新浪微部落格戶端微博源內容的灰底圓角效果,這個時候我們就可以使用Shape。
1、介紹
Shape Drawable Resources是指一個XML檔案,它定義了幾何形狀,包括顏色和漸變。
放在res/Drawable資料夾下,檔名即為資源id,可以在其他layout中呼叫R.drawable.filename,
shape包含矩形、橢圓形、行、環形。
2、使用
下面以為一個TextView設定一個漸變色的邊框為例進行介紹,第三部分對具體屬性含義進行介紹
2.1 定義一個漸變色的矩形shape,檔案路徑res/drawable/gradient_box.xml
[html] view plaincopyprint?- <?xmlversion="1.0"encoding="utf-8"?>
- <shapexmlns:android="http://schemas.android.com/apk/res/android"
- android:shape="rectangle">
- <gradient
- android:startColor="#FFFF0000"
-
android:endColor
- android:angle="45"/>
- <paddingandroid:left="7dp"
- android:top="7dp"
- android:right="7dp"
- android:bottom="7dp"/>
- <cornersandroid:radius="8dp"/>
- </shape>
- <TextView
-
android:background
- android:layout_height="wrap_content"
- android:layout_width="wrap_content"/>
其中 android:background="@drawable/gradient_box"表示設定背景為 gradient_box 這個drawable
或者在後臺程式中設定
[html] view plaincopyprint?- Resources res = getResources();
- Drawable shape = res. getDrawable(R.drawable.gradient_box);
- TextView tv = (TextView)findViewByID(R.id.textview);
- tv.setBackground(shape);
3、屬性介紹
xml定義如下
[html] view plaincopyprint?- <?xmlversion="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邊線的設定