2012-05-14 29 views
7

我在XML文件中創建按鈕這樣的:按鈕並繪製左

<Button 
     android:id="@+id/call_button" 
     android:layout_width="match_parent" 
     android:layout_height="0dp" 
     android:layout_marginTop="30dp" 
     android:background="@drawable/button" 
     android:layout_weight="40" 
     android:drawableLeft="@drawable/symbol_phone" 
     android:paddingLeft="20dp" 
     android:drawablePadding="-25dp" 
     android:text="Call" 
     android:textColor="@color/white" 
     /> 

我想知道我可以在活動做drawableLeft。我知道這很愚蠢,但我需要在活動中做到這一點,因爲我在那裏創建按鈕。如何在我的活動中執行與XML文件中的操作相同的操作?我需要添加drawableLeft和drawable填充和填充左側。 這是我如何活動

Button button1 = new Button(this); 
button1.setLayoutParams(new RelativeLayout.LayoutParams(buttonWidth, buttonHeight)); 
button1.setText(systemTexts.getShowCallButton()); 
button1.setBackgroundDrawable(new          
button1.setTextColor(Color.parseColor(buttonTextColor)); 

回答

20
Drawable image = getContext().getResources().getDrawable(R.drawable.icon); 
image.setBounds(0, 0, 60, 60); 
button.setCompoundDrawables(image, null, null, null); 

做到這一點

更新:

由於getContext().getResources().getDrawable現在過時,而不是使用:

Drawable image = ContextCompat.getDrawable(getApplicationContext(),R.drawable.icon); 
    image.setBounds(0, 0, 60, 60); 
    button.setCompoundDrawables(image, null, null, null); 
5

試試這個,

Drawable icon= getContext().getResources().getDrawable(R.drawable.icon); 
button.setCompoundDrawablesWithIntrinsicBounds(icon, null, null, null); 
-1

您可以使用下面的代碼

<Button android:text="@string/button_label" 
android:id="@+id/buttonId" 
android:layout_width="160dip" 
android:layout_height="60dip" 
android:layout_gravity="center" 
android:textSize="13dip" 
android:drawableLeft="@drawable/button_icon" 
android:drawablePadding="2dip" 
android:paddingLeft="30dip" 
android:paddingRight="26dip" 
android:singleLine="true" 
android:gravity="center" /> 

它將由填充TI的文字和圖片同時管理

+0

我想你不回答這個問題,OP想要以編程方式進行。 – Joffrey

0

你可以試試這個:

txtVw.setCompoundDrawables(R.drawable.img_nature, 0, 0, 0);