通過代碼設置radiobutton不同方位圖標的兩種方法


 

更換radiobutton中的圖片在xml中很好設置,但對於初學者如何在代碼中設置還是不容易找的。沒法子,通過看原版api找到兩個方法,setCompoundDrawables和setCompoundDrawablesWithIntrinsicBounds。

下面交給大家方法。

第一個方法:setCompoundDrawablesWithIntrinsicBounds(Drawable left, Drawable top, Drawable right, Drawable 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獲取。——筆者翻譯

1                 button = (RadioButton) group.getChildAt(i);
2                 Resources res = TabTest.this.getResources();
3                 Drawable myImage = res.getDrawable(R.drawable.home);
4                 button.setCompoundDrawablesWithIntrinsicBounds(null, myImage, null, null);

如圖第一個按鈕:

 

 第二種方法:setCompoundDrawables(Drawable left, Drawable top, Drawable right, Drawable 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:組件的高度。

如代碼:

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

只要調整好寬和高。效果也是一樣的。這個方法的好處就是不按比例,寬高可以打破原有的大小及比例!如圖,我調的y軸有點不對齊。

 

總結:radiobutton設置不同方位的圖標的方法有以上兩種,如果想手動設置大小的話就要用setCompoundDrawables,事先要給Drawable設置setBounds。

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

 

本人經驗有限,代碼有不對或不妥的地方請大牛指出!謝謝

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM