在我們的項目中,常常會碰到圖片與文字混排的問題。解決這類問題的方法有非常多,本文給出的方法不是唯一的。僅僅有依據實際場景才干找到更適合的方法。
本文主要通過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。
<span style="font-size:18px;"> <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"/></span>
當中, 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)來實現
<span style="font-size:18px;"> <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></span>
事實上也能夠通過java代碼來實現圖片和文字的混排。