2011-09-13 16 views
21

estoy usando un Button creado usando siguiente códigoCómo configurar la imagen del botón de fondo a través de código

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

Tengo una imagen en la trayectoria @drawable/new_todo_image a establecer como fondo para el botón. ¿Cómo configurarlo en el Button mediante programación?

Respuesta

74

imagen de fondo conjunto para el botón que se encuentra en la carpeta dibujable a continuación, utilizar a continuación el código

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

Gracias ... su código funcionó para mí –

0

probar esto:

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

estoy consiguiendo error siguiente: El setBackgroundDrawable método (Disponibles) en el tipo de vista no es aplicable a los argumentos (int) –

+0

que tengo editó la respuesta. Probar ahora. –

+0

btn.setBackgroundResource (R.drawable.new_todo_image); Este código se ajusta al requisito. Y gracias por mejor sugerencia –

7

Prueba este para:

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

a partir de 2014, esto está en desuso. – katzenhut

1

Trate como esto

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

En Android Studio para establecer botón Fondo de la imagen de escritura siguiente código:

int image_resid = getApplicationContext().getResources().getIdentifier("image_name", "drawable", getApplicationContext().getPackageName()); 
button.setBackgroundResource(image_resid); 
Cuestiones relacionadas