1. 程式人生 > >Android 動態設定TextView的drawableLeft等屬性

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