开发者

how to set Image and text at the center of the button

i have set my buttons width to 开发者_运维百科fill_parent.

so Is it possible to set Image and text at center of button.

there is option for drawable_Left but it aligns image on left side of button...

I want something like this.


.... [image][text].... |


Thanks:


Try this: first set background for the button then set image by using android:drawableTop="" and then set the text by android:text=""


use android:gravity="center_vertical" in your layout


<Button android:text="Button" android:id="@+id/button1"
    android:layout_height="wrap_content" android:background="@drawable/icon"
    android:layout_width="200dp" android:gravity="center"></Button>

Hope it helps ;


your should you Relative layout for getting the solution of your problem using the blow code put it on your xml file

android:layout_centerHorizontal ="true"


first give the gravity to center then use drawable_Left.


Here is an utility function to center a left image and text inside a Button:

public static void centerImageAndTextInButton(Button button) {
    Rect textBounds = new Rect();
    //Get text bounds
    CharSequence text = button.getText();
    if (text != null && text.length() > 0) {
        TextPaint textPaint = button.getPaint();
        textPaint.getTextBounds(text.toString(), 0, text.length(), textBounds);
    }
    //Set left drawable bounds
    Drawable leftDrawable = button.getCompoundDrawables()[0];
    if (leftDrawable != null) {
        Rect leftBounds = leftDrawable.copyBounds();
        int width = button.getWidth() - (button.getPaddingLeft() + button.getPaddingRight());
        int leftOffset = (width - (textBounds.width() + leftBounds.width()) - button.getCompoundDrawablePadding()) / 2 - button.getCompoundDrawablePadding();
        leftBounds.offset(leftOffset, 0);
        leftDrawable.setBounds(leftBounds);
    }
}

It uses the width of the Button to make the calculation, so you must check that you are calling this in the right place. That is, the width should be other than zero. For instance, if you want to use it in onCreate use button.getViewTreeObserver().addOnGlobalLayoutListener(...call it onGlobalLayout...).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜