如何将图片和文本置于按钮中央

5

我已将按钮宽度设置为fill_parent

那么,是否可以将图像和文本设置在按钮中心。

drawable_Left选项,但它将图像对齐到按钮的左侧...

我想要这样的效果。


.... [图像][文本].... |


谢谢:


使用drawable_Left后,你可以设置padding。 - Lavanya
6个回答

2
尝试这样做:首先为按钮设置背景,然后使用 android:drawableTop="" 设置图像,最后使用 android:text="" 设置文本。请注意保留 HTML 标签。

0

你应该使用相对布局来解决问题,将以下代码放在你的XML文件中。

android:layout_centerHorizontal ="true"

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

希望这有所帮助;

0

这是一个实用函数,用于将左侧图像和文本居中放置在 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);
    }
}

它使用Button的宽度进行计算,因此您必须检查您是否在正确的位置调用它。也就是说,宽度应该不为零。例如,如果您想在onCreate中使用它,请使用button.getViewTreeObserver().addOnGlobalLayoutListener(...在onGlobalLayout中调用...)


0

在您的布局中使用 android:gravity="center_vertical"


0

首先给gravity属性设置为center,然后使用drawable_Left


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接