Android:在 Button 或 ImageButton 上组合文本和图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1532876/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 03:13:16  来源:igfitidea点击:

Android: combining text & image on a Button or ImageButton

androidimagetextbutton

提问by znq

I'm trying to have an image (as the background) on a button and add dynamically, depending on what's happening during run-time, some text above/over the image.

我正在尝试在按钮上放置一个图像(作为背景)并根据运行时发生的情况动态添加图像上方/上方的一些文本。

If I use ImageButtonI don't even have the possibility to add text. If I use ButtonI can add text but only define an image with android:drawableBottomand similar XML attributes as defined here.

如果我使用,ImageButton我什至无法添加文本。如果我使用,Button我可以添加文本,但只能定义具有android:drawableBottom此处定义的类似 XML 属性的图像。

However these attributes only combine text & image in x- and y-dimensions, meaning I can draw an image around my text, but not below/under my text (with the z-axis defined as coming out of the display).

然而,这些属性仅在 x 和 y 维度中组合文本和图像,这意味着我可以在我的文本周围绘制图像,但不能在我的文本下方/下方(z 轴定义为从显示中出来)。

Any suggestions on how to do this? One idea would be to either extend Buttonor ImageButtonand override the draw()-method. But with my current level of knowledge I don't really know how to do this (2D rendering). Maybe someone with more experience knows a solution or at least some pointers to start?

关于如何做到这一点的任何建议?一种想法是扩展ButtonImageButton覆盖draw()-method。但是以我目前的知识水平,我真的不知道如何做到这一点(2D 渲染)。也许有更多经验的人知道解决方案或至少有一些开始的指示?

采纳答案by m_vitaly

You can call setBackground()on a Buttonto set the background of the button.

您可以调用setBackground()aButton来设置按钮的背景。

Any text will appear above the background.

任何文本都会出现在背景上方。

If you are looking for something similar in xml there is: android:backgroundattribute which works the same way.

如果您正在 xml 中寻找类似的东西,则有: android:background以相同方式工作的属性。

回答by OneWorld

For users who just want to put Background, Icon-Image and Text in oneButtonfrom different files: Set on a Buttonbackground, drawableTop/Bottom/Rigth/Left and paddingattributes.

对于只想将Button不同文件中的背景、图标图像和文本放在一起的用户:设置Button背景、drawableTop/Bottom/Rigth/Left 和填充属性。

<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/home_btn_test"
        android:drawableTop="@drawable/home_icon_test"
        android:textColor="#FFFFFF"
        android:id="@+id/ButtonTest"
        android:paddingTop="32sp"
        android:drawablePadding="-15sp"
        android:text="this is text"></Button>

For more sophisticated arrangement you also can use RelativeLayout(or any other layout) and make it clickable.

对于更复杂的安排,您还可以使用RelativeLayout(或任何其他布局)并使其可点击。

Tutorial:Great tutorial that covers both cases: http://izvornikod.com/Blog/tabid/82/EntryId/8/Creating-Android-button-with-image-and-text-using-relative-layout.aspx

教程:涵盖这两种情况的精彩教程:http: //izvornikod.com/Blog/tabid/82/EntryId/8/Creating-Android-button-with-image-and-text-using-relative-layout.aspx

回答by schlingel

There's a much better solution for this problem.

这个问题有一个更好的解决方案。

Just take a normal Buttonand use the drawableLeftand the gravityattributes.

只需取一个法线Button并使用drawableLeftgravity属性。

<Button
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:drawableLeft="@drawable/my_btn_icon"
  android:gravity="left|center_vertical" />

This way you get a button which displays a icon in the left side of the button and the text at the right site of the icon vertical centered.

通过这种方式,您将获得一个按钮,该按钮在按钮的左侧显示一个图标,在图标的右侧位置显示垂直居中的文本。

回答by Dhina k

enter image description here

在此处输入图片说明

     <Button
            android:layout_width="0dp"
            android:layout_weight="1"
            android:background="@drawable/home_button"
            android:drawableLeft="@android:drawable/ic_menu_edit"
            android:drawablePadding="6dp"
            android:gravity="left|center"
            android:height="60dp"
            android:padding="6dp"
            android:text="AndroidDhina"
            android:textColor="#000"
            android:textStyle="bold" />

回答by Kieran

Just use a LinearLayout and pretend it's a Button- setting backgroundand clickableis the key:

只需使用 LinearLayout 并假装它是Button- 设置background可点击是关键:

<LinearLayout
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@android:drawable/btn_default"
    android:clickable="true"
    android:orientation="horizontal" >

    <ImageView
        android:id="@+id/img"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:layout_marginLeft="5dp"
        android:src="@drawable/image" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:layout_margin="5dp"
        android:text="Do stuff" />
</LinearLayout>

回答by CMA

just replace

只需更换

android:background="@drawable/icon"

with

android:background="@android:color/transparent"
android:drawableTop="@drawable/[your background image here]"

izz a pretty good trick.. ;)

izz 一个不错的技巧.. ;)

回答by Oscar Salguero

I took a different approach from the ones stated here, and it is working really well, so I wanted to share it.

我采用了与此处所述方法不同的方法,并且效果很好,所以我想分享它。

I'm using a Style to create a custom button with image at the left and text at the center-right. Just follow the 4 "easy steps" below:

我正在使用样式创建一个自定义按钮,左侧为图像,右侧为文本。只需按照下面的 4 个“简单步骤”进行操作:

I. Create your 9 patches using at least 3 different PNG files and the tool you have at: /YOUR_OWN_PATH/android-sdk-mac_x86/tools/./draw9patch. After this you should have:

I. 使用至少 3 个不同的 PNG 文件和您在以下位置拥有的工具创建 9 个补丁:/YOUR_OWN_PATH/android-sdk-mac_x86/tools/./draw9patch。在此之后,您应该:

button_normal.9.png, button_focused.9.png and button_pressed.9.png

button_normal.9.png、button_focused.9.png 和 button_pressed.9.png

Then download or create a 24x24 PNG icon.

然后下载或创建一个 24x24 的 PNG 图标。

ic_your_icon.png

ic_your_icon.png

Save all in the drawable/ folder on your Android project.

将所有内容保存在 Android 项目的 drawable/ 文件夹中。

II. Create a XML file called button_selector.xml in your project under the drawable/ folder. The states should be like this:

二、在您的项目中的 drawable/ 文件夹下创建一个名为 button_selector.xml 的 XML 文件。状态应该是这样的:

<item android:state_pressed="true" android:drawable="@drawable/button_pressed" />
<item android:state_focused="true" android:drawable="@drawable/button_focused" />
<item android:drawable="@drawable/button_normal" />

III. Go to the values/ folder and open or create the styles.xml file and create the following XML code:

三、转到 values/ 文件夹并打开或创建 styles.xml 文件并创建以下 XML 代码:

<style name="ButtonNormalText" parent="@android:style/Widget.Button">
    <item name="android:textColor" >@color/black</item>
    <item name="android:textSize" >12dip</item>
    <item name="android:textStyle" >bold</item>
    <item name="android:height" >44dip</item>
    <item name="android:background" >@drawable/button_selector</item>
    <item name="android:focusable" >true</item>
    <item name="android:clickable" >true</item>
</style>

<style name="ButtonNormalTextWithIcon" parent="ButtonNormalText">
    <item name="android:drawableLeft" >@drawable/ic_your_icon</item>
</style>

ButtonNormalTextWithIcon is a "child style" because it is extending ButtonNormalText (the "parent style").

ButtonNormalTextWithIcon 是一种“子样式”,因为它扩展了 ButtonNormalText(“父样式”)。

Note that changing the drawableLeft in the ButtonNormalTextWithIcon style, to drawableRight, drawableTop or drawableBottom you can place the icon in other position with respect to the text.

请注意,将 ButtonNormalTextWithIcon 样式中的 drawableLeft 更改为 drawableRight、drawableTop 或 drawableBottom,您可以将图标放置在相对于文本的其他位置。

IV. Go to the layout/ folder where you have your XML for the UI and go to the Button where you want to apply the style and make it look like this:

四、转到您拥有 UI 的 XML 的 layout/ 文件夹,然后转到要应用样式的 Button 并使其看起来像这样:

<Button android:id="@+id/buttonSubmit" 
android:text="@string/button_submit" 
android:layout_width="fill_parent" 
android:layout_height="wrap_content" 
style="@style/ButtonNormalTextWithIcon" ></Button>

And... voilà! You got your button with an image at the left side.

还有……瞧!你的按钮在左边有一个图像。

For me, this is the better way to do it! because doing it this way you can manage the text size of the button separately from the icon you want to display and use the same background drawable for several buttons with different icons respecting the Android UI Guidelines using styles.

对我来说,这是更好的方法!因为这样做,您可以将按钮的文本大小与要显示的图标分开管理,并对具有不同图标的多个按钮使用相同的背景可绘制,并遵守使用样式的 Android UI 指南。

You can also create a theme for your App and add the "parent style" to it so all the buttons look the same, and apply the "child style" with the icon only where you need it.

您还可以为您的应用程序创建一个主题并向其添加“父样式”,以便所有按钮看起来都相同,并仅在需要的地方应用带有图标的“子样式”。

回答by Salman Khursheed Khaleeqi

 <Button android:id="@+id/imeageTextBtn" 
        android:layout_width="240dip"
        android:layout_height="wrap_content"
        android:text="Side Icon With Text Button"
        android:textSize="20sp"
        android:drawableLeft="@drawable/left_side_icon"         
        />   

回答by Kalai.G

You can use drawableTop(also drawableLeft, etc) for the image and set text below the image by adding the gravityleft|center_vertical

您可以对图像使用drawableTop(也drawableLeft等),并通过添加gravityleft|center_vertical

<Button
            android:id="@+id/btn_video"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:background="@null"
            android:drawableTop="@drawable/videos"
            android:gravity="left|center_vertical"
            android:onClick="onClickFragment"
            android:text="Videos"
            android:textColor="@color/white" />

回答by Khemraj

Important Update

重要更新

Don't use normal android:drawableLeftetc... with vector drawables, else it will crashin lower API versions. (I have faced it in live app)

不要使用普通android:drawableLeft等...与矢量可绘制对象,否则它会在较低的 API 版本中崩溃。(我在实时应用中遇到过)

For vector drawable

对于矢量可绘制

If you are using vector drawable, then you must

如果您使用矢量可绘制,那么您必须

  • Have you migrated to AndroidX? if not you must migrate to AndroidX first. It is very simple, see what is androidx, and how to migrate?
  • It was released in version 1.1.0-alpha01, so appcompat version should be at least 1.1.0-alpha01. Current latest version is 1.1.0-alpha02, use latest versions for better reliability, see release notes - link.

    implementation 'androidx.appcompat:appcompat:1.1.0-alpha02'

  • Use AppCompatTextView/AppCompatButton/AppCompatEditText

  • Use app:drawableLeftCompat, app:drawableTopCompat, app:drawableRightCompat, app:drawableBottomCompat, app:drawableStartCompatand app:drawableEndCompat
  • 您迁移到 AndroidX 了吗?如果不是,您必须先迁移到 AndroidX。很简单,看看什么是androidx,如何迁移?
  • 它是在版本中发布的1.1.0-alpha01,所以 appcompat 版本应该至少是1.1.0-alpha01. 当前最新版本是1.1.0-alpha02,使用最新版本以获得更好的可靠性,请参阅发行说明 -链接

    implementation 'androidx.appcompat:appcompat:1.1.0-alpha02'

  • 使用AppCompatTextView/ AppCompatButton/AppCompatEditText

  • 使用app:drawableLeftCompatapp:drawableTopCompatapp:drawableRightCompatapp:drawableBottomCompatapp:drawableStartCompatapp:drawableEndCompat

For regular drawable

对于常规可绘制

If you don't need vector drawable, then you can

如果您不需要矢量可绘制,那么您可以

  • use android:drawableLeft, android:drawableRight, android:drawableBottom, android:drawableTop
  • You can use either regular TextView, Button& EditTextor AppCompatclasses.
  • 使用android:drawableLeft, android:drawableRight, android:drawableBottom,android:drawableTop
  • 您可以使用常规TextViewButton&EditTextAppCompat类。

You can achieve Outputlike below -

您可以实现如下输出-

output

输出