Android中利用shape定制控件边框

本文介绍了一种在Android开发中为控件添加特定方向边框的方法,通过定义不同方向的边框样式并使用layer-list进行组合,可以灵活地实现各种边框效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在日常android的开发过程中,我们会遇到这样的一个需求。我只想给控件加左边框或者右边框,当然方法有很多种了。下面就不列举了,我就分享一个我认为比较好的实现方式吧。


首先要了解shape中gradient的原理,这里就不多说了,不明白的就自己去google。

分别定义左边框、底边框、右边框、上边框。

left-border

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">
  <!-- left border -->
  <gradient
      android:angle="0"
      android:startColor="#3666"
      android:centerColor="@android:color/transparent"
      android:centerX="1%"
      />
</shape>


bottom-border

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">
  <!-- bottom border -->
  <gradient
      android:angle="90"
      android:startColor="#3F00"
      android:centerColor="@android:color/transparent"
      android:centerX="1%"
      />
</shape>

right-border

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">
  <!-- right border -->
  <gradient
      android:angle="180"
      android:startColor="#3666"
      android:centerColor="@android:color/transparent"
      android:centerX="1%"
      />
</shape>

top-border

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">
  <!-- top border -->
  <gradient
      android:angle="270"
      android:startColor="#3666"
      android:centerColor="@android:color/transparent"
      android:centerX="1%"
      />
</shape>


好了,左边框、底边框、右边框、上边框已经定义好了,接下来就是排列组合问题了。

举例:

底边框+右边框

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
  <item
      android:drawable="@drawable/bottom_border"/>
  <item android:drawable="@drawable/right_border"/>
</layer-list>


以此类推,eclipse中的layout或者android studio的preview中可能看不到渲染效果,但是运行时效果的真实展现的。大家试试吧

转自 http://www.th7.cn/Program/Android/201503/401232.shtml


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值