2011-09-13 36 views
21

Tôi đang sử dụng một Button tạo sử dụng đoạn mã sauLàm thế nào để thiết lập các hình nền nút thông qua mã

LinearLayout ll = new LinearLayout(this); 
ll.setOrientation(LinearLayout.VERTICAL); 

Button btn = new Button(this); 
btn.setOnClickListener(newtodobtn); 
btn.setText("New Todo"); 

btn.setBackgroundDrawable(new Button(this).getBackground()); 

ll.addView(btn); 

Tôi có một hình ảnh trên đường đi @drawable/new_todo_image để thiết lập làm nền cho nút. Làm thế nào để đặt nó vào Button lập trình?

Trả lời

74

cho hình nền thiết lập cho nút đó nằm trong thư mục drawable sau đó sử dụng mã dưới đây

btn.setBackgroundResource(R.drawable.new_todo_image); 
+0

Cảm ơn bạn ... mã của bạn đã hoạt động cho tôi –

0

thử điều này:

btn.setBackgroundDrawable(getResources().getDrawable(R.drawable.new_todo_image)); 
+0

Tôi nhận được lỗi sau: Phương pháp setBackgroundDrawable (drawable) trong các loại Xem không áp dụng cho các đối số (int) –

+0

Tôi có đã chỉnh sửa câu trả lời. Thử ngay bây giờ. –

+0

btn.setBackgroundResource (R.drawable.new_todo_image); Mã này phù hợp với yêu cầu. Và cảm ơn đề xuất tốt hơn –

7

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

btn.setBackgroundDrawable(getResources().getDrawable(R.drawable.new_todo_image)); 
+3

tính đến năm 2014, điều này không được chấp nhận. – katzenhut

1

Hãy thử như

này
final int sdk = android.os.Build.VERSION.SDK_INT; 
    if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) 
    { 
     mBtn.setBackgroundDrawable(getResources().getDrawable(R.drawable.new_todo_image)); 
    } 
    else 
     { 
     mBtn.setBackground(getResources().getDrawable(R.drawable.new_todo_image)); 
     } 
1

Trong studio android để thiết lập nền Button Image ghi mã sau:

int image_resid = getApplicationContext().getResources().getIdentifier("image_name", "drawable", getApplicationContext().getPackageName()); 
button.setBackgroundResource(image_resid); 
Các vấn đề liên quan