开发者

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


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


==>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.


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)


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜