【问题标题】:how to set Image and text at the center of the button如何在按钮的中心设置图像和文本
【发布时间】:2011-05-19 09:24:24
【问题描述】:

我已将按钮宽度设置为 fill_parent

所以是否可以在按钮中心设置图像和文本。

drawable_Left 有一个选项,但它会对齐按钮左侧的图像...

我想要这样的东西。


.... [图片][文字].... |


谢谢:

【问题讨论】:

  • 使用drawable_Left后可以设置padding

标签: android


【解决方案1】:

试试这个:首先为按钮设置背景,然后使用android:drawableTop=""设置图像,然后使用android:text=""设置文本

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:
      <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>
      

      希望对你有帮助;

      【讨论】:

        【解决方案4】:

        你应该把它放在你的xml文件中

        android:layout_centerHorizontal ="true"
        

        【讨论】:

          【解决方案5】:

          首先将gravity 提供给center,然后使用drawable_Left

          【讨论】:

            【解决方案6】:

            这是一个实用函数,用于在 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(...call it onGlobalLayout...)

            【讨论】:

              猜你喜欢
              • 2011-06-16
              • 2011-04-06
              • 2019-06-13
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多