1. 程式人生 > >Android-如何給View新增邊框,邊框顏色和線的粗細可以自定義

Android-如何給View新增邊框,邊框顏色和線的粗細可以自定義

一、使用場景

有時在開發中,遇到向表格形式的佈局,這時該怎麼辦?

如果只是簡單的一條橫線或者豎線,直接使用TextView控制元件,寬或者高固定1dp或者2dp,高或者寬match parent,在定義一個background="#FF0000",這樣就實現了單一的線條功能。線條的顏色就是指定的背景顏色,線粗就是寬或者高。

但是如果四條邊框都有線,總不能一條一條的去拼接吧,這多費事。解決方法有2中,第一種方法是使用一張有背景線條的9-patch圖片;方法二,自己製作一個shape佈局,在需要使用的地方通過background屬性引用即可。

下面就介紹第2種方法:

二、關鍵程式碼

1.shape_textview_cart.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <stroke
        android:width="1dp"
        android:color="#ebebeb" />

    <padding
        android:bottom="1dp"
        android:left="1dp"
        android:right="1dp"
        android:top="1dp" />

    <solid android:color="#00000000" />

</shape>

2.引用的佈局檔案
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="120dp"
    android:layout_marginLeft="2dp"
    android:layout_marginRight="2dp"
    android:background="@drawable/shape_textview_cart"
    android:orientation="horizontal" >

    <ImageView
        android:id="@+id/cart_image"
        android:layout_width="120dp"
        android:layout_height="120dp"
        android:layout_marginRight="1dp"
        android:src="@drawable/qzone" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >

        <include layout="@layout/include_cart_listview_item_right_01" />

        <include layout="@layout/include_cart_price_number" />
    </LinearLayout>

</LinearLayout>
3.效果圖