Android開發系列(十八):自訂控制項樣式在drawable檔案夾下的XML實現,androiddrawable
在Android開發的過程中,我們經常需要對控制項的樣式做一下改變,可以通過用增加背景圖片的方式進行改變,但是背景圖片放多了肯定會使得APK檔案變的很大。
我們可以用自訂屬性shape來實現。
shape:
gradient -- 對應色彩坡形。 startcolor、endcolor就不多說了。 android:angle 是指從哪個角度開始變。
solid -- 填充。
stroke -- 描邊。
corners -- 圓角。
padding -- 定義內容離邊界的距離。
我們先來看一下效果:
下邊我們用具體的代碼來示範一下:
首先,建立一個項目,然後我們在main.xml編輯:
<span style="font-size:18px;"><?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content"android:layout_marginTop="10dp" android:text="示範文本" android:textSize="14pt" android:textColor="#565656" android:background="@drawable/bg_border" /> <!-- 通過android:drawableLeft繪製一張圖片 --><TextView android:layout_width="fill_parent"android:layout_height="wrap_content"android:text="示範文本2"android:textSize="24pt"android:background="@drawable/bg_border2"/></LinearLayout></span>
可以看到,在上邊的兩個TextView的android:background屬性,用到了@drawable/bg_border和@drawable/bg_border2這兩個檔案
然後,我們在@drawable檔案夾下邊建立這兩個Android xml檔案:
bg_border.xml:
<span style="font-size:18px;"><?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android"> <!-- 填充:設定背景顏色 --><solid android:color="#ffffff"/><!-- 設定邊框 --><stroke android:width="5px" android:color="#873600" android:dashWidth="5dip" /><!-- 定義內邊距 --><padding android:top="20dip" /> </shape></span>
bg_border2.xml:
<span style="font-size:18px;"><?xml version="1.0" encoding="UTF-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <!-- 指定圓角矩形的4個圓角的半徑 --> <corners android:topLeftRadius="20px" android:topRightRadius="5px" android:bottomRightRadius="20px" android:bottomLeftRadius="5px"/> <!-- 指定邊框線條的寬度和顏色 --><stroke android:width="4px" android:color="#f0f" /><!-- 指定使用漸層背景色,使用sweep類型的漸層顏色從紅色→綠色→藍色 --><gradient android:startColor="#f00" android:centerColor="#0f0" android:endColor="#00f" android:type="sweep"/></shape></span>
我們看下我們的工程目錄檢視:
Eclipse下怎在drawable-mdpi檔案夾下面建立一個<selector>的xml檔案?
在drawable-mdpi檔案夾上右鍵:建立(new)-檔案(file),輸入myselector.xml 就可建立檔案
我在做android項目的ui,往drawable檔案夾裡面匯入圖片,layout下的mainxml也做了相應的更改,但有錯誤
這種錯誤的原因有很多啊,也許是你main.xml裡面的圖片名字寫錯了,也許是你eclipse又抽風了。你放圖片進去後,先重新整理下,不行的話重啟eclipse,總之這不是個大問題,很容易解決的