1. 程式人生 > >xml佈局中實現文字下劃線的效果

xml佈局中實現文字下劃線的效果

最近在專案中正好碰到需求:給文字實現下劃線的效果,在網上搜索了下,有提供方法,但是我想完全依靠xml佈局去實現,然後試驗了幾次,最終只用了TextView做出瞭如下效果:

這裡寫圖片描述

下劃線圖片程式碼:

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

   <stroke
       android:width="1dp"
       android:color="#0042F4"
/>
<size android:height="2dp" android:width="90dp"/> </shape>

現在看TextView的設定:

?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
="wrap_content" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" android:layout_marginTop="20dp" android:background="@drawable/system_bg1" android:orientation="vertical">
<TextView android:layout_width
="match_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:padding="10dp" android:text="請看如下的下劃線效果圖" android:textColor="#FFFFFF" android:textSize="18sp"/>
<LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginLeft="50dp" android:orientation="horizontal"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:gravity="center" android:text="1、" android:textColor="#0042F4"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:drawablePadding="-3dp" android:drawableBottom="@drawable/underline" android:gravity="center" android:text="下劃線下劃線" android:textColor="#0042F4"/> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_marginTop="10dp" android:layout_marginBottom="10dp" android:layout_marginLeft="50dp" android:layout_height="match_parent" android:orientation="horizontal"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:gravity="center" android:text="2、" android:textColor="#0042F4"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:drawableBottom="@drawable/underline1" android:gravity="center" android:drawablePadding="-3dp" android:text="下劃線下劃線" android:textColor="#0042F4"/> </LinearLayout> </LinearLayout>

以上就是完全依靠xml佈局實現的。其中我認為最關鍵的一步就是在TextView中將drawablePadding設定為負值。將字型和圖片之間的間距進一步縮小,實現了下劃線的效果。

相關推薦

no