Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 實現文字與圖片的混排

編輯:關於 Android 程式設計

在專案中經常會碰到圖片與文字混排的問題,解決方法有很多,本文提供的方法並非唯一,實際上仍需依場景選擇更合適的方案。本文主要透過 XML 佈局來實現圖片與文字的水平混排。

1. 利用 TextView 實現混排

透過 TextView 的 drawable 屬性即可實現圖文混排:

  • android:drawableBottom:在文字下方輸出一個 drawable(如圖片)。
  • android:drawableLeft:在文字左邊輸出一個 drawable。
  • android:drawableRight:在文字右邊輸出一個 drawable。
  • android:drawableTop:在文字正上方輸出一個 drawable。
  • android:drawablePadding:設定文字與 drawable 之間的間隔,可設為負數,需與上述方向屬性搭配使用才有效果。
<TextView
    android:id="@+id/my_tv"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="在線"
    android:textColor="#85898f"
    android:layout_marginTop="5dp"
    android:drawablePadding="5dp"
    android:drawableLeft="@drawable/user_online" />

其中,android:drawablePadding 很好地解決了圖片與文字的間距問題。

2. 利用 RelativeLayout / LinearLayout 組合

也可以透過 RelativeLayout 加入 TextView 與 ImageView 來實現:

<RelativeLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >

    <ImageView
        android:id="@+id/my_iv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/user_online"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:layout_marginLeft="5dp" />

    <TextView
        android:id="@+id/my_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/my_iv"
        android:layout_centerVertical="true"
        android:layout_marginLeft="5dp" />
</RelativeLayout>

當然,也可以透過 Java 程式碼來實現圖文混排,可依需求彈性調整。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved