Android网格布局中按钮之间的边距

5

我想创建一个包含按钮的网格布局,但是默认情况下这些按钮之间存在空格,而我不需要。.xml文件如下:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_gravity="center">
    <HorizontalScrollView android:id="@+id/HorizontalScrollView"
                          android:layout_width="wrap_content"
                          android:layout_height="wrap_content"
                          android:layout_gravity="center">
    <GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:id="@+id/gridLayout"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center">
    </GridLayout>
  </HorizontalScrollView>
</ScrollView>

我创建按钮并将其添加到网格布局的代码:

for (int rowCounter = 0; rowCounter < DIMENSION; rowCounter++)
    for (int columnCounter = 0; columnCounter < DIMENSION; columnCounter++) {
        Button b = new Button(this);
        b.setText(" ");
        GridLayout.LayoutParams params = new GridLayout.LayoutParams();
        params.setMargins(0, 0, 0, 0);
        b.setLayoutParams(params);
        gridLayout.addView(b);
    }

这是一个它的外观图像: image

使用HierarchyViewer查看按钮之间是否真的存在边距。 - pskink
1个回答

3

Android默认按钮有一些填充空间。
如果你不想要那个空间,你需要为你的按钮创建一个自定义背景。

这是一个例子:

button_dark_gradient.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:state_pressed="true" >
         <shape>
            <gradient
                android:startColor="#00000000"
                android:centerColor="#FFFFFF"
                android:endColor="#00000000"
                android:angle="270" />
            <padding
                android:left="10dp"
                android:top="10dp"
                android:right="10dp"
                android:bottom="10dp" />          
        </shape>

        <shape>
            <gradient
                android:startColor="#00CFCCCE"
                android:centerColor="#FFFFFF"
                android:endColor="#00BAB8B9"
                android:angle="270" />
            <padding
                android:left="10dp"
                android:top="10dp"
                android:right="10dp"
                android:bottom="10dp" />            
        </shape>        
    </item>
    <item>
        <shape>
            <gradient
                android:startColor="#00CFCCCE"
                android:centerColor="#FFFFFF"
                android:endColor="#00BAB8B9"
                android:angle="270" />
        </shape>
    </item>

</selector>  

将您的按钮背景设置为此可绘制对象。

b.setBackground(getResources().getDrawable(R.drawable.button_dark_gradient));

谢谢您先生,那就是解决方案,我稍微调整了一下颜色和渐变,并将填充设置为0,现在看起来很好。 - Jones

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接