• 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作为按钮背景图片

  • 相关阅读:
    postgres 错误duplicate key value violates unique constraint 解决方案
    Golang包管理工具之govendor的使用
    《算法竞赛进阶指南》0x26广搜变形 HDOJ3085 双向BFS
    《算法竞赛进阶指南》0x26广搜变形 POJ3635
    《算法竞赛进阶指南》0x26广搜变形 电路维修 01最短路问题
    《算法竞赛进阶指南》0x25广度优先搜索 推箱子游戏 双重BFS
    《算法竞赛进阶指南》0x25广度优先搜索 多源floodfill
    《算法竞赛进阶指南》0x25广度优先搜索 POJ3322 Bloxorz I
    NETCORE
    VUE- 异步等待方法嵌套
  • 原文地址:https://www.cnblogs.com/ayqy/p/4130570.html
Copyright © 2020-2023  润新知