1. Problem Restatement
The description in the summary might not be clear enough; the problem is shown in the image below:

How to eliminate the gap between Button1 and Button2, as well as the gaps between the buttons and the left/right boundaries?
2. Root Cause
The gaps appearing here are actually transparent parts in the button's background image, as shown below: (both buttons are pressed simultaneously)

Because the gap is part of the Button itself, setting margin and padding to 0 cannot eliminate it (as for setting a negative margin, well, does that even count as a solution?)
3. Solutions and Verification
- Setting the Button's style attribute:
<Button style="?android:attr/buttonBarButtonStyle"/>
(Initial)
(Both buttons are pressed)Effect of Solution 1: Eliminates the gaps without affecting the default click effect (background turns blue). - Setting the Button's style to a custom style (or directly setting the Button's background attribute to a custom image):
<style name="mybutton"> <item name="android:background" >@drawable/whitecolor</item> <item name="android:padding">0dp</item> <item name="android:gravity">center</item> </style>
(Initial/Pressed)Effect of Solution 2: Eliminates the gaps, but the default click effect is gone. - Setting the Button's background to transparent:
android:background="#00000000"
(Initial/Pressed)Effect of Solution 3: Eliminates the gaps, but the default click effect is gone (same result as Solution 2). - Replacing LinearLayout with 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>
Effect of Solution 4: Cannot eliminate the gaps. - Using a custom selector as the Button's background:
<?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"
(Left button is pressed)Effect of Solution 5: Eliminates the gaps without affecting the default click effect (similar to Solution 1, but better as it allows custom backgrounds).
4. Summary
The key to eliminating button gaps lies in changing the `background` attribute. Using an image with no transparency at the borders as the background will solve the problem.
I recommend using Solution 5: Using a custom `selector` as the button's background image.
No comments yet. Be the first to share your thoughts.