android给View设置上下左右边框

来源:互联网 发布:淘宝热卖是什么 编辑:程序博客网 时间:2024/05/22 15:56

一、使用场景

有时在开发中,遇到向表格形式的布局,这时该怎么办?

如果只是简单的一条横线或者竖线,直接使用TextView控件,宽或者高固定1dp或者2dp,高或者宽match parent,在定义一个background="#FF0000",这样就实现了单一的线条功能。线条的颜色就是指定的背景颜色,线粗就是宽或者高。

但是如果四条边框都有线,总不能一条一条的去拼接吧,这多费事。解决方法有2中,第一种方法是使用一张有背景线条的9-patch图片;方法二,自己制作一个shape布局,在需要使用的地方通过background属性引用即可。

下面就介绍第2种方法:

二、关键代码

1.shape_textview_cart.xml

[html] view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <shape xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:shape="rectangle" >  
  4.   
  5.     <stroke  
  6.         android:width="1dp"  
  7.         android:color="#ebebeb" />  
  8.   
  9.     <padding  
  10.         android:bottom="1dp"  
  11.         android:left="1dp"  
  12.         android:right="1dp"  
  13.         android:top="1dp" />  
  14.   
  15.     <solid android:color="#00000000" />  
  16.   
  17. </shape>  

2.引用的布局文件

[html] view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="120dp"  
  5.     android:layout_marginLeft="2dp"  
  6.     android:layout_marginRight="2dp"  
  7.     android:background="@drawable/shape_textview_cart"  
  8.     android:orientation="horizontal" >  
  9.   
  10.     <ImageView  
  11.         android:id="@+id/cart_image"  
  12.         android:layout_width="120dp"  
  13.         android:layout_height="120dp"  
  14.         android:layout_marginRight="1dp"  
  15.         android:src="@drawable/qzone" />  
  16.   
  17.     <LinearLayout  
  18.         android:layout_width="match_parent"  
  19.         android:layout_height="match_parent"  
  20.         android:orientation="vertical" >  
  21.   
  22.         <include layout="@layout/include_cart_listview_item_right_01" />  
  23.   
  24.         <include layout="@layout/include_cart_price_number" />  
  25.     </LinearLayout>  
  26.   
  27. </LinearLayout>  
3.效果图
0 0
原创粉丝点击