Android GridView绘制分隔线

Eri*_*hen 24 android gridview border divider

我想知道在GridView中的项目(当前是文本视图)之间绘制分隔符的最简单方法.我能想到的唯一方法是在这些文本视图周围绘制边框,因此在组合时,它们看起来像连续的水平和垂直分隔线.

列表视图有一个setDivider()但不是gridviews吗?

谢谢.

Fen*_*res 35

如果您只想要简单的线条作为边框,那么更简单的是为GridView正确的填充和间距设置背景颜色:

<GridView
    (...)
    android:background="@color/LightGold"
    android:listSelector="@android:color/transparent"
    android:horizontalSpacing="1dip"
    android:verticalSpacing="1dip"
    android:paddingLeft="1dip"
    android:paddingTop="1dip" />
Run Code Online (Sandbox Code Playgroud)

  • 如果您有两列,并且具有奇数个项目,则会为空白空间添加纯色背景 (4认同)
  • 没工作,我只是一个纯色,没有间距. (2认同)
  • 这仅在您稍后单独设置每个单元格的背景时才有效.作为一个缺点,它会导致透支. (2认同)

Cha*_*ase 28

不幸的是,在查看源代码之后,除了采用向每个单元格添加边框的方法之外,我看不到任何简单的方法来添加边框.作为参考,我将在此发布我的解决方案.

list_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal"
    android:background="@drawable/list_selector">

    <!-- Cell contents -->

</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

list_selector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item 
        android:state_selected="true" 
        android:drawable="@drawable/item_border_selected" 
    />
    <item 
        android:state_pressed="true" 
        android:drawable="@drawable/item_border_selected" 
    />
    <item
        android:drawable="@drawable/item_border" 
    />
</selector>
Run Code Online (Sandbox Code Playgroud)

item_border.xml

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid 
        android:color="@android:color/transparent" 
    />
    <stroke 
        android:width="1px" 
        android:color="@color/list_divider" 
    />
</shape>
Run Code Online (Sandbox Code Playgroud)

item_border_selected.xml

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid 
        android:color="@color/list_select" 
    />
    <stroke 
        android:width="1px" 
        android:color="@color/list_divider" 
    />
</shape>
Run Code Online (Sandbox Code Playgroud)

items_view.xml

<?xml version="1.0" encoding="utf-8"?>
<GridView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_marginLeft="-1px"
    android:layout_marginRight="-1px"
    android:listSelector="@android:color/transparent"
/>
Run Code Online (Sandbox Code Playgroud)

由于所有线条在加入相邻单元格时尺寸加倍,因此我将分割器尺寸设为1px而不是1dp,因此在某些屏幕上看起来不会太大.此外,我使网格视图具有负边距以隐藏任一侧的线条.我希望这可以帮助别人.