【问题标题】:How to center the text inside a Button regardless of drawableLeft?无论drawableLeft如何,如何将Button内的文本居中?
【发布时间】:2015-04-09 20:18:36
【问题描述】:

我希望文本以Button 为中心。但是每当我将android:drawableLeft xml 属性添加到Button 时,它都会偏移文本。我该如何解决?

我设法解决它的唯一方法是在android:drawablePadding 中设置一个负数:

但我正在寻找一种更清洁的解决方案来实现它。

【问题讨论】:

    标签: android button textview drawable


    【解决方案1】:

    不幸的是,这是 Button 行为,我同意你的观点,负填充是一种肮脏的 hack,所以我将提出另外两个对我来说听起来不那么脏的 hack,因为它们依赖于预期的行为(负填充虽然有效,但不是设计使然):

    • 将按钮上的 android:paddingRight 设置为可绘制对象的大小
    • 创建一个与左侧可绘制对象大小相同但所有透明像素的可绘制对象,并将其作为右侧可绘制对象。

    【讨论】:

      【解决方案2】:

      所以我最终选择了取其轻巧的方法,那就是将可绘制对象和文本放在 RelativeLayout 中:

      <RelativeLayout
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          style="@style/Button.ButtonGray"
          android:id="@+id/share_button">
      
          <ImageView
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:src="@drawable/btn_share"/>
      
          <TextView
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:textColor="@android:color/black"
              android:textStyle="bold"
              android:layout_centerInParent="true"
              style="@style/TextNormalWeight"
              android:text="@string/post_share"/>
      
      </RelativeLayout>
      

      RelativeLayout 然后接收点击事件并表现得像一个按钮。

      【讨论】:

        【解决方案3】:

        android:gravity="center_vertical"

        【讨论】:

        • 不。按钮样式中的gravity 已经是center(不仅仅是center_vertical)。
        【解决方案4】:

        不幸的是,没有干净的方法可以做到这一点。一种相当直接的方法是在按钮的另一侧设置一个大小相同的透明 ColorDrawable。

        val drawableSize = button.height // adjust this as desired of course
        
        realDrawable.setBounds(0, 0, drawableSize, drawableSize)
        
        val emptyDrawable = ColorDrawable(Color.TRANSPARENT).apply {
            setBounds(0, 0, drawableSize, drawableSize)
        }
        
        button.setCompoundDrawables(realDrawable, null, emptyDrawable, null)
        

        【讨论】:

          【解决方案5】:

          它适用于:

          android:gravity="center"
          

          【讨论】:

            猜你喜欢
            • 2012-06-30
            • 1970-01-01
            • 1970-01-01
            • 2011-09-16
            • 2011-02-08
            • 2017-01-18
            • 1970-01-01
            • 2012-04-14
            • 1970-01-01
            相关资源
            最近更新 更多