Shrenik
Shrenik

Reputation: 399

How to add the image and text to button in code ? and not via xml

How to add the image and text to button in code ? and not via xml

Upvotes: 0

Views: 2506

Answers (4)

Barmaley
Barmaley

Reputation: 16363

I suppose it should be something like this(I have never tried it, but in similar situation it will works):

Button myButton = new Button(this);
LinearLayout layout=new LinearLayout(this);
layout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));

ImageView imageView=new ImageView(this);
TextView textView=new TextView(this);
//...

//add text+image to layout
layout.addView(textView);
layout.addView(imageView);

//add layout to button
myButton.addView(layout);

Upvotes: 0

dsafcdsge4rfdse
dsafcdsge4rfdse

Reputation: 258

You create a button...

    Button myButton = new Button(this);

... then you add the text...

    myButton.setText("MyButton");

... after that you add the background image...

  • if you use an png file you could use :

    myButton.setBackgroundResource(R.drawable.myimg);
    

    (don't forget that you have to put the png file in the drawable folder)

  • or you could try to use the setBackgroundDrawable (Drawable d)

Upvotes: 0

Thrawn80
Thrawn80

Reputation: 351

With an investigationtime of 2 minutes you could find this very easily. But this might help you:

ButtonName.setText("Content of button text");
String myJpgPath = "/sdcard/pic.jpg";
Bitmap image_b = BitmapFactory.decodeFile(myJpgPath);
BitmapDrawable image_d = new BitmapDrawable(image_b);

then use image_b for .setBackgroundDrawable

ButtonName.setBackgroundDrawable(image_d);

Upvotes: 3

Kakey
Kakey

Reputation: 4024

==>public void setCompoundDrawables (Drawable left, Drawable top, Drawable right, Drawable bottom)

Sets the Drawables (if any) to appear to the left of, above, to the right of, and below the text. Use null if you do not want a Drawable there. The Drawables must already have had setBounds(Rect) called.

Upvotes: 1

Related Questions