Android UI 利用Drawable Shape給控件加邊框/立體效果

在軟開中,經常需要對原生的控件UI進行修改,最近項目由於UI沒到位,所有有些帶邊框的有立體效果的UI要自己實現,實現方法是用XML寫Shape。

關於Drawable Shape XML的詳細內容官方API doc提供的還是挺詳細的:http://developer.android.com/guide/topics/resources/drawable-resource.html#Shape

ListView Items加邊框構成立體效果:



通過圖像工具放大鏡的幫助,其實可以發現一個Item背景其實是5個矩形組成:


所以我們可以通過5個矩形shape的top和bottom的擠壓畫出我們上圖的效果:list_item_border.xml

<?xml version="1.0" encoding="UTF-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="#D2D6D8" />
        </shape>
    </item>
    <item android:top="1dp"> 
        <shape android:shape="rectangle">
            <solid android:color="#C2C5C9" />
        </shape>
    </item>
    <item android:top="1dp" android:bottom="1dp"> 
        <shape android:shape="rectangle">
            <solid android:color="#F3F3F3" />
        </shape>
    </item>
    <item android:top="2dp" android:bottom="1dp"> 
        <shape android:shape="rectangle">
            <solid android:color="#EBEBEA" />
        </shape>
    </item>
    <item android:bottom="2dp" android:top="2dp">
        <shape android:shape="rectangle">
            <solid android:color="#E6E6E6"/>
        </shape>
    </item>
</layer-list>
最後把Item的背景設置成這個就可以了:
android:background="@drawable/list_item_border"


項目中還遇到過一個情況,就要多個TextView: EditText對的下方用一條線分隔開,效果如下:



同樣用放大鏡可以看到分割線其實是4個矩形(或者是4條線),但是不能和上面一樣寫,不然會被最後一個矩形把圖像顏色都佔滿(這個問題我糾結很久)。應該和畫線條一下寫矩形:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item>
        <shape>
            <solid android:color="#E4E4E4"/>
            <size android:height="1dp"/>
        </shape>
    </item>
    <item android:top="1dp">
        <shape>
            <solid  android:color="#B8BDC2"/>
            <size android:height="1dp"/>
        </shape>
    </item>
    <item android:top="2dp">
        <shape>
            <solid  android:color="#EBECED"/>
            <size android:height="1dp"/>
        </shape>
    </item>
    <item android:top="3dp">
        <shape>
            <solid  android:color="#ECECEC"/>
            <size android:height="1dp"/>
        </shape>
    </item>
</layer-list>

就是給它們定好高度,然後一條條向下壓。


補充下,圓角和可見邊框的實現:其實很簡單,分別採用Shape的<corners /> 和 <stroke />實現

圓角關鍵在於android:radius屬性,這個是半徑,數字越大,圓角越圓。

可見邊框設置寬度就可以了,還有一個就是dash虛線的屬性。這樣實現邊框都是全部的(矩形就是四邊),如果想實現單邊,那麼你就只能用本文最開始的那個方法用兩個(多個)矩形拼出只有一個邊框的矩形。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章