2011-08-03 17 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を使用することができます実行時にそれを使用する方法についての手掛かりはありません。開発者のドキュメントのそのプロパティの説明に移動してください。あなたが見つかるでしょう関連メソッド実行時にサポートされている場合。すなわちFor DrawableLeft

+0

だからどこで私はこの方法でdrawableを設定するのですか? –

+1

+1プログラムでTextViewのandroid:drawableLeftを設定する作業。 Thanxの仲間 –

+23

+1のチップを追加します。それは先端のために文書 – gmjordan

13

hereこの方法を参照するには、setCompoundDrawablesWithIntrinsicBounds(int,int,int,int)を参照してください。

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

ヒント:あなたは任意のXML属性を知っているときはいつでも、あなたが左にDrawableのための画像

例を望んでいないところ

3

あなたがのTextViewにDrawableのを設定するため、次のいずれかの方法を使用することができます

の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

関連する問題