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一樣!

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