最近在學做一個新聞客戶端,發現它的帶圖標按鈕都是直接用ImageView
+TextView
的布局。
大概是這樣
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="15dp"
android:layout_marginTop="15dp"
android:orientation="horizontal">
<ImageView
android:layout_width="36dp"
android:layout_height="36dp"
android:background="@drawable/ic_account_circle_white_24dp" />
<TextView
android:id="@+id/tv_login"
android:layout_width="wrap_content"
android:layout_height="36dp"
android:layout_marginLeft="10dp"
android:gravity="center_vertical"
android:text="請登錄"
android:textColor="@android:color/white"
android:textSize="18sp" />
</LinearLayout>
如果只是一個這樣的按鈕的話,那也無所謂,問題是需求中有很多個這樣的按鈕,這樣一長串的布局真的很難維護,而且一點都不優雅。那么問題來了,怎么簡化代碼。
兩個方案:
- 自定義控件
將這段布局封裝在自定義控件中,不過對于這種簡單的布局,根本沒必要,況且有了下面的解決方案
- 使用TextView自帶的
drawable
屬性
豁然開朗了,好像問題一下子就解決了,可是調試布局不是一句話就那么簡單的
先簡單粗暴的使用android:drawableLeft
屬性設置圖標
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/white"
>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#bbb"
android:drawableLeft="@mipmap/home"
android:text="首頁"
android:textColor="@color/holo_blue_dark"
android:textSize="22sp"/>
</RelativeLayout>
發現效果變成了這樣
1.png
字體與圖標不能再垂直方向上對齊
不怕,設置一下android:gravity="center_vertical"
,再看
2.png
注意:
android:gravity
屬性不會影響圖片,也就是說當設置了android:gravity="bottom"
屬性之后,
只有文本會處于底部
此時的效果已經不錯了,但是我還想要讓圖片與文字稍稍有點間距
試試用padding
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/white"
>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#bbb"
android:drawableLeft="@mipmap/home"
android:text="首頁"
android:paddingLeft="28dp"
android:gravity="center_vertical"
android:textColor="@color/holo_blue_dark"
android:textSize="22sp" />
</RelativeLayout>
3.png
發現圖片也移動了,但是圖片與文字的間距并沒有改變,幸好,TextView
有一個 android:drawablePadding
屬性
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/white"
>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#bbb"
android:drawableLeft="@mipmap/home"
android:text="首頁"
android:drawablePadding="28dp"
android:gravity="center_vertical"
android:textColor="@color/holo_blue_dark"
android:textSize="22sp" />
</RelativeLayout>
4.png
這時候的圖文按鈕已經能達到想要的效果了,代碼也簡潔了很多
注意:
android:drawablePadding
屬性所設置的間距是圖標與文本的間距,而不是圖標的內邊距