Android 動態設置TextView的drawableLeft等屬性


   首先,我們在開發過程中,會經常使用到android:drawableLeft="@drawable/ic_launcher"這些類似的屬性:

  關於這些屬性的意思,無非是在你的textView文本的上下左右處添加一個圖片。比如下面這么一段代碼:

 

 

<TextView

android:id="@+id/text_drawable"
android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="@string/hello_world"

android:drawableLeft="@drawable/ic_launcher"

android:drawablePadding="4dp"

/>

 

它設置了在文本的左邊,顯示一個小圖標,效果如下:


 

  而在一些情況下,我們需要在動態在代碼中設置文本周圍的圖標,那該如何呢,首先,我們看下TextView提供了哪些方法:

乍眼看去,挺多方法的,好,我們主要介紹setCompoundDrawables和setCompoundDrawablesWithIntrinsicBounds。

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

  setCompoundDrawables(left, top, right, bottom)及setCompoundDrawablesWithIntrinsicBounds(left, top, right, bottom),它們的意思是設置Drawable顯示在text的左、上、右、下位置。

  但是兩者有些區別:
  setCompoundDrawables 畫的drawable的寬高是按drawable.setBound()設置的寬高,
所以才有The Drawables must already have had setBounds(Rect) called,即使用之前必須使用Drawable.setBounds設置Drawable的長寬。

  而setCompoundDrawablesWithIntrinsicBounds是畫的drawable的寬高是按drawable固定的寬高,
所以才有The Drawables' bounds will be set to their intrinsic bounds.即通過getIntrinsicWidth()與getIntrinsicHeight()獲得。

  一般,建議使用setCompoundDrawablesWithIntrinsicBounds,這樣你即無需設置Drawables的bounds了。

 

 看下代碼:

 

 

TextView textDrawable = (TextView) findViewById(R.id.text_drawable);

Drawable drawableLeft = getResources().getDrawable(

R.drawable.ic_launcher);

textDrawable.setCompoundDrawablesWithIntrinsicBounds(drawableLeft,

null, null, null);

textDrawable.setCompoundDrawablePadding(4);


 效果和以上直接通過android:drawableLeft一樣!


免責聲明!

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



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