2011-08-03 55 views
205

我在這裏有一個xml的textView。在TextView中以編程方式設置左繪圖

<TextView 
     android:id="@+id/bookTitle" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:layout_weight="1" 
     android:drawableLeft="@drawable/checkmark" 
     android:gravity="center_vertical" 
     android:textStyle="bold" 
     android:textSize="24dip" 
     android:maxLines="1" 
     android:ellipsize="end"/> 

正如你所看到的,我將DrawableLeft設置爲xml。

我想更改代碼中的drawable。

無論如何要去做這件事嗎?或者在文本視圖的代碼中設置drawableLeft?

回答

584

您可以使用setCompoundDrawablesWithIntrinsicBounds(int left, int top, int right, int bottom)

集0,你不希望圖像

示例可繪製在左邊:

TextView textView = (TextView) findViewById(R.id.myTxtView); 
textView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.icon, 0, 0, 0); 

提示:當你知道任何XML屬性但不知道如何在運行時使用它。只需轉到開發人員文檔中該屬性的描述即可。如果在運行時支持,則會發現相關方法。即For DrawableLeft

+0

那麼我在哪裏設置drawable在這個方法? –

+1

+1其工作原理是以編程方式爲TextView設置android:drawableLeft。 Thanx隊友 –

+23

+1添加提示。這應該是開發人員在使用文檔 – gmjordan

3

您可以使用以下任一方法的設置上的TextView的繪製對象:

1- setCompoundDrawablesWithIntrinsicBounds(int, int, int, int)

2- setCompoundDrawables(Left_Drawable, Top_Drawable, Right_Drawable, Bottom_Drawable)

而且擺脫資源繪製你可以使用:

getResources().getDrawable(R.drawable.your_drawable_id); 
+0

不,setCompoundDrawablesWithIntrinsicBounds(int,int,int,int)是API Levet 3從您自己的鏈接... – BrainCrash

+0

哦對不起!我已更新我的答案 –

-7
static private Drawable **scaleDrawable**(Drawable drawable, int width, int height) { 

    int wi = drawable.getIntrinsicWidth(); 
    int hi = drawable.getIntrinsicHeight(); 
    int dimDiff = Math.abs(wi - width) - Math.abs(hi - height); 
    float scale = (dimDiff > 0) ? width/(float)wi : height/
      (float)hi; 
    Rect bounds = new Rect(0, 0, (int)(scale * wi), (int)(scale * hi)); 
    drawable.setBounds(bounds); 
    return drawable; 
} 
+0

這並不回答問題。預期與TextView相關的答案。 – Rick

相關問題