如何Center图标和文字的一款Android按钮的宽度设置为QUOT&;填充母" [英] How to center icon and text in a android button with width set to "fill parent"

查看:187
本文介绍了如何Center图标和文字的一款Android按钮的宽度设置为QUOT&;填充母"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想有一个Android按钮使用图标+文字里面居中。我使用的是drawableLeft属性设置IMG,这项工作做得很好,如果按钮具有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 img, this work 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 fix 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 suggestion how could I archive that?

推荐答案

安卓drawableLeft始终保持安卓以下属性来从左边框的距离。当按钮没有被设置为机器人:宽度=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!

使用的Andr​​oid 4.0(API级别14)可以使用<一个href="http://developer.android.com/reference/android/R.attr.html#drawableStart">android:drawableStart属性将一个绘制的文本的开始。唯一的向后兼容的解决方案,我想出了是使用 ImageSpan 创建文字+图片Spannable:

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);

在我来说,我需要还调整了android:按钮的重力属性,使它看起来居中:

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" />

这篇关于如何Center图标和文字的一款Android按钮的宽度设置为QUOT&;填充母&QUOT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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