Android开发消除横向排列的多个Button之间的空隙

一.问题重述

 

摘要里描述的可能不太清楚,问题如下图:

如何消除Button1和Button2之间的空隙,以及Button与左右边界之间的空隙?

二.问题根源

这里出现的空隙其实是Button的背景图片中的透明部分,如下图:(两个按钮被同时按下)

因为间隙是Button自身的一部分,所以设置margin和padding为0也无法消除(至于把margin设置为负值,额,这算解决方案吗?)

三.解决方案及验证

  1. 设置Button的style属性:
    <Button style="?android:attr/buttonBarButtonStyle"/>
    

    (初始)

    (两个按钮都被按下)

    方案1的效果:可以消除间隙,并且不影响按钮默认的点击效果(背景变蓝)

  2. 设置Button的style为自定义style(或者直接设置Button的background属性为自定义图片):
    <style name="mybutton">
        <item name="android:background" >@drawable/whitecolor</item>
        <item name="android:padding">0dp</item>
        <item name="android:gravity">center</item>
    </style>
    

    (初始/按下)

    方案2的效果:可以消除间隙,但按钮默认的点击效果没了

  3. 设置Button的background为透明色:
    android:background="#00000000"
    

    (初始/按下)

    方案3的效果:可以消除间隙,但按钮默认的点击效果没了(和方案2效果一样)

  4. 把LinearLayout换为TableLayout:
    <TableLayout
        android:stretchColumns="*"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >
        <TableRow>
            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_column="0"
                android:text=" Button1" />
            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_column="1"
                android:text=" Button2" />
        </TableRow>
    </TableLayout>
    

    方案4的效果:无法消除间隙

  5. 自定义selector作为Button背景:
    <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:drawable="@drawable/highlight"
            android:state_pressed="true"></item>
        <item android:drawable="@drawable/normal"></item>
    </selector>
    
    android:background="@drawable/bg_btn"
    

    (左边按钮被按下)

    方案5的效果:可以消除间隙,并且不影响按钮的默认点击效果(和方案1的效果类似,比方案1更好一些,可以自定义按钮背景)

四.总结

消除按钮间隙的关键在于改background属性,用边框不含透明色的图片作为按钮的背景即可消除间隙

消除按钮间隙建议使用方案5:自定义selector作为按钮背景图片

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值