2011-08-03 60 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

相关问题