实现 图片+文字 一起居中显示的 Button

在Android中,原生Button添加图标和文字后,图标可能无法与文字居中。本文介绍了两种方法实现图片和文字一起居中的Button:1. 使用LinearLayout组合布局,虽然方便但代码量大;2. 使用Button结合自定义onDraw方法,分别展示了左右和上下居中的实现效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

实现 图片+文字 一起居中显示的 Button

Android 中原生的 Button 可以添加图标和文字(通过控制标签来实现图标相对于文字的位置):
标签:

android:drawableLeft,
android:drawableRight,
android:drawableTop,
android:drawableBottom;

但是如果使用上述标签,就会发现图标会贴着 Button 边缘,无法和文字一起居中。
例如:
在这里插入图片描述

实现 图片+文字 一起居中显示的 Button的几种方法
1.使用 LinearLayout组合布局
代码:

<LinearLayout
        android:id="@+id/btn_add"
        android:layout_width="360dp"
        android:layout_height="50dp"
        android:layout_marginTop="20dp"
        android:background="@drawable/roundrect"
        android:gravity="center"
        android:layout_gravity="center"
        android:orientation="horizontal">

        <ImageButton
            android:id="@+id/id_add_img"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#00000000"
            android:src="@mipmap/add" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:text="@string/btn_AddDevice"
            android:textSize="18sp" />

    </LinearLayout>
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值