android 設置圖片小妙招 setCompoundDrawables與setCompoundDrawablesWithIntrinsicBounds

手工設置文本與圖片相對位置時,常用到如下方法:

setCompoundDrawables(left, top, right, bottom)

setCompoundDrawablesWithIntrinsicBounds(left, top, right, bottom)

意思是設置Drawable顯示在text的左、上、右、下位置。

但是兩者有些區別:
setCompoundDrawablesWithIntrinsicBounds(left, top, right, bottom)

api原文爲:
Sets the Drawables (if any) to appear to the left of, above, to the right of, and below the text. Use null if you do not want a Drawable there. The Drawables’ bounds will be set to their intrinsic bounds.

意思大概就是:可以在上、下、左、右設置圖標,如果不想在某個地方顯示,則設置爲null。圖標的寬高將會設置爲固有寬高,既自動通過getIntrinsicWidth和getIntrinsicHeight獲取。

setCompoundDrawables(left, top, right, bottom)

api原文爲:
Sets the Drawables (if any) to appear to the left of, above, to the right of, and below the text. Use null if you do not want a Drawable there. The Drawables must already have had setBounds(Rect) called.

意思大概就是:可以在上、下、左、右設置圖標,如果不想在某個地方顯示,則設置爲null。但是Drawable必須已經setBounds(Rect)。意思是你要添加的資源必須已經設置過初始位置、寬和高等信息。

這下就明白了,這個方法要先給Drawable設置setBounds(x,y,width,height);

x:組件在容器X軸上的起點 y:組件在容器Y軸上的起點 width:組件的長度 height:組件的高度。
如代碼:

Resources res = TabTest.this.getResources();
Drawable myImage = res.getDrawable(R.drawable.home);
myImage.setBounds(1, 1, 100, 100);
button.setCompoundDrawables(null, myImage, null, null);

總結:設置不同方位的圖標的方法有以上兩種,

如果想手動設置大小的話就要用setCompoundDrawables,事先要給Drawable設置setBounds。

如果按照原有比例大小顯示圖片就使用setCompoundDrawablesWithIntrinsicBounds

發佈了63 篇原創文章 · 獲贊 6 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章