2013-08-16 50 views
7

Tôi đang sử dụng một nút
Programatically thay đổi drawableLeft của Button

<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" /> 

và thay đổi màu chữ của nó với:

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

nhưng không thể hiểu how to change its image??

+0

hãy nhìn vào http://developer.android.com/guide/topics/ui/controls /button.html#CustomBackground để tạo kiểu cho nút của bạn – Eluvatar

+0

đặt như thế này button.setBackground (R.drawable.ic_launcher); bên trong trình nghe onclick. – Aravin

+0

Bản sao có thể có của [Làm cách nào để thiết lập drawableLeft trên nút Android?] (Http://stackoverflow.com/questions/4502605/how-to-programatically-set-drawableleft-on-android-button) – Varun

Trả lời

38

Hãy thử điều này:

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

Reference

0

tôi khuyên bạn thay vì sử dụng nút bạn sử dụng Imageview và thêm người nghe onclick vào nó. Bằng cách đó bạn có thể chỉ cần làm Imageview.setbitmap(bitmap) và tạo ra một bitmap từ một trong drawables bạn

2

Để làm điều này, bạn có thể sử dụng

setCompoundDrawables (...);

phương pháp. Xin lưu ý rằng đi kèm với TextView, không phải Nút.

Đây là làm thế nào để sử dụng nó:

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

Trích từ: How to programmatically set drawableLeft on Android button?

+0

Cách đặt hình ảnh trong Quyền lợi của chế độ xem văn bản –

12

Cách an toàn nhất để thiết lập các drawable trái mà không thay đổi giá trị của các sản phẩm khác (trên cùng, bên phải và dưới):

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

điểm tốt !, cảm ơn !! – Bhimbim

0

chỉ cần làm theo mã này tôi hy vọng nó thực sự hữu ích cho bạn ..

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); 
     } 
    } 
});