2013-08-16 122 views
7

的drawableLeft我使用一個按鈕
編程方式更改按鈕

<Button 
     android:id="@+id/zoom" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:background="@color/trans" 
     android:drawableLeft="@drawable/left_img" 
     android:fontFamily="arial" 
     android:text="My Name is " 
     android:textSize="50sp" /> 

,並改變其文本顏色:

zoom.setTextColor(Color.parseColor("voilet")); 

,但無法理解how to change its image??

+0

看看http://developer.android.com/guide/topics/ui/controls /button.html#CustomBackground來設置你的按鈕 – Eluvatar

+0

像這樣button.setBackground(R.drawable.ic_launcher);在onclick監聽器中。 – Aravin

+0

[如何以編程方式設置drawableLeft on Android按鈕?](http://stackoverflow.com/questions/4502605/how-to-programatically-set-drawableleft-on-android-button) – Varun

回答

38

試試這個:

int imgResource = R.drawable.left_img; 
button.setCompoundDrawablesWithIntrinsicBounds(imgResource, 0, 0, 0); 

Reference

0

我建議不要使用按鈕,而要使用Imageview併爲其添加onclick監聽器。這樣,你可以做Imageview.setbitmap(bitmap)並創建您的可繪製的一個位圖

2

要做到這一點,你可以使用

setCompoundDrawables(...);

方法。請注意,TextView,而不是按鈕。

這是如何使用它:

Drawable img = getContext().getResources().getDrawable(R.drawable.yourimage); 
img.setBounds(0, 0, 60, 60); // set the image size 
txtVw.setCompoundDrawables(img, null, null, null); 

來自:How to programmatically set drawableLeft on Android button?

+0

如何設置圖像在textview –

12

設置左繪製沒有最安全的方法改變其他drawable的值(上,右,和底部):

Drawable[] drawables = textViewExample.getCompoundDrawables(); 
textViewExample.setCompoundDrawablesWithIntrinsicBounds(leftDrawable, drawables[1], drawables[2], drawables[3]); 
+0

好點!!,謝謝!! – Bhimbim

0

只要按照這個代碼,我希望這對你非常有幫助..

boolean isIconChange; 
button.setOnClickListener(new OnClickListener() { 

    @Override 
    public void onClick(View arg0) { 
     isIconChange = !isIconChange; 
     if(isIconChange){ 
      button.setCompoundDrawablesWithIntrinsicBounds(R.drawable.like, 0, 0, 0); 
      button.setTextColor(Color.BLACK); 
     } else { 
      button.setCompoundDrawablesWithIntrinsicBounds(R.drawable.dislike, 0, 0, 0); 
      button.setTextColor(Color.RED); 
     } 
    } 
}); 
相關問題