如何在宽度设置为“填充父级"的 android 按钮中居中图标和文本 [英] How to center icon and text in a android button with width set to "fill parent"

查看:36
本文介绍了如何在宽度设置为“填充父级"的 android 按钮中居中图标和文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个 Android 按钮,里面有图标+文本.我正在使用 drawableLeft 属性来设置图像,如果按钮的宽度为 "wrap_content",这很有效,但我需要拉伸到最大宽度,所以我使用宽度 "fill_parent".这将我的图标直接移动到按钮的左侧,我希望图标和文本都在按钮内居中.

I want to have an Android Button with icon+text centered inside it. I'm using the drawableLeft attribute to set the image, this works well if the button has a width of "wrap_content" but I need to stretch to max width so I use width "fill_parent". This moves my icon straight to the left of the button and I want both icon and text centered inside the button.

我尝试设置填充,但这仅允许提供固定值,因此这不是我需要的.我需要在中心对齐图标+文本.

I've try setting up the padding but this only allows to give a fixed value so it is not what I need. I need to have icon+text aligned in the center.

<Button 
    android:id="@+id/startTelemoteButton" 
    android:text="@string/start_telemote"
    android:drawableLeft="@drawable/start"
    android:paddingLeft="20dip"
    android:paddingRight="20dip"            
    android:width="fill_parent"
    android:heigh="wrap_content" />

关于我如何实现这一目标的任何建议?

Any suggestions on how I could achieve that?

推荐答案

android:drawableLeft 始终保持 android:paddingLeft 与左边框的距离.当按钮没有设置为android:width="wrap_content"时,会一直挂在左边!

android:drawableLeft is always keeping android:paddingLeft as a distance from the left border. When the button is not set to android:width="wrap_content", it will always hang to the left!

在 Android 4.0(API 级别 14)中,您可以使用 android:drawableStart 属性在文本的开头放置一个drawable.我想出的唯一向后兼容的解决方案是使用 ImageSpan 来创建一个文本+图像可跨度:

With Android 4.0 (API level 14) you can use android:drawableStart attribute to place a drawable at the start of the text. The only backward compatible solution I've come up with is using an ImageSpan to create a Text+Image Spannable:

Button button = (Button) findViewById(R.id.button);
Spannable buttonLabel = new SpannableString(" Button Text");
buttonLabel.setSpan(new ImageSpan(getApplicationContext(), R.drawable.icon,      
    ImageSpan.ALIGN_BOTTOM), 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
button.setText(buttonLabel);

就我而言,我还需要调整 Button 的 android:gravity 属性以使其看起来居中:

In my case I needed to also adjust the android:gravity attribute of the Button to make it look centered:

<Button
  android:id="@+id/button"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:minHeight="32dp"
  android:minWidth="150dp"
  android:gravity="center_horizontal|top" />

这篇关于如何在宽度设置为“填充父级"的 android 按钮中居中图标和文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆