動態爲TextView設置drawableRight

       在寫TextView的這個屬性的drawableRight時,一般都是在xml裏面寫好的,但是我們有時候的需求是想在代碼中動態的添加的效果,那麼接下來說說具體的方法。

      

<TextView
        android:id="@+id/Title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:drawableRight="@drawable/check_down"
        android:gravity="center_vertical"
        android:textSize="24dip"
        android:maxLines="1"
        android:ellipsize="end"/>

我們寫在xml的時候,都是這麼寫的。那代碼呢?我們發現TextView他有一個方法

public void  setCompoundDrawables  (Drawable left, Drawable top, Drawable right, Drawable bottom);

這個方法呢,就是可以在Java代碼動態的畫 左上右下幾個方向類似於xml中的

android:drawableLeft="@drawable/icon"
android:drawableTop="@drawable/icon"
android:drawableRight="@drawable/icon"
android:drawableButtom="@drawable/icon"
具體在代碼中的用法是:

Drawable drawable = getResources().getDrawable(R.drawable.spinner_checked);
drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight()); //設置邊界
titleTv.setCompoundDrawables(null, null, drawable, null);//畫在右邊
大家也還可以通過這個方法實現
public void setCompoundDrawablesWithIntrinsicBounds (Drawable left,
Drawable top, Drawable right, Drawable bottom)





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章