天天看點

android自定義圖檔文本,Android 實作文字與圖檔的混排

在我們的項目中,常常會碰到圖檔與文字混排的問題。解決這類問題的方法有非常多,本文給出的方法不是唯一的。僅僅有依據實際場景才幹找到更适合的方法。

本文主要通過xml布局來實作圖檔與文字的混排(水準排列)。

1.利用TextView實作圖檔與文字混排,

android:drawableBottom在text的下方輸出一個drawable。如圖檔。

假設指定一個顔色的話會把text的背景設為該顔色。而且同一時候和background使用時覆寫後者。

android:drawableLeft在text的左邊輸出一個drawable,如圖檔。

android:drawablePadding設定text與drawable(圖檔)的間隔,

與drawableLeft、 drawableRight、drawableTop、drawableBottom一起使用,可設定為負數。單獨使用沒有效果。

android:drawableRight在text的右邊輸出一個drawable。

android:drawableTop在text的正上方輸出一個drawable。

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:drawablePaddingh非常好的攻克了圖檔與文字的間距問題。

2.TextView動态的設定圖檔

Drawable drawable= context.getResources().getDrawable(R.drawable.text_img);

// 調用setCompoundDrawables時。必須調用Drawable.setBounds()方法,否則圖檔不顯示

drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());

textView.setCompoundDrawables(drawable, null, null, null); //設定左圖示

3.利用RelativeLayout(LinearLayout) 加入 TextView 和 ImageView(ButtonView)來實作

android:layout_width="wrap_content"

android:layout_height="wrap_content" >

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"

/>

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"

/>

事實上也能夠通過java代碼來實作圖檔和文字的混排。