Android LinearLayout: 分割线不显示

5

我正在尝试设置一个分隔线,用于我的应用程序中的列表。我已经制作了“dicedivider”的XML代码,如下所示:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="line">
<stroke
   android:width="1px"
   android:color="@color/divider_Color"
   />

</shape>

我试图将它设置为LinearLayout的分隔符可绘制对象,如下所示:

protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    diceCount = 0;
    diceList = (LinearLayout) this.findViewById(R.id.main_Dice_List);

    diceList.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE);
    diceList.setDividerDrawable(this.getResources().getDrawable(R.drawable.dicedivider));
    diceList.setDividerPadding(5);
    addDice();
}

然而,不管怎样,应用程序未显示任何分隔线。我甚至尝试将其直接嵌入XML中,但没有成功。

我在Android编码方面非常新手。您有什么想法我出了什么问题吗?


请看代码示例这里,我也支持旧设备。 - android developer
不要忘记 android:showDividers 属性! - Fattie
4个回答

1
在res/drawable目录下创建一个名为mydivider.xml的文件,然后添加以下形状:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <size android:width="1dip" />
    <solid android:color="#ffffff" />
</shape>

将形状添加为您的布局分隔符。
<LinearLayout android:id="@+id/linearlayout"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:divider="@drawable/mydivider"
    android:showDividers="middle"
    android:dividerPadding="22dp">    
</LinearLayout>

0
你可以在 XML 中使用。
<View 
        android:layout_width="fill_parent"
        android:layout_height="1dp"       android:Background="@android:color/darker_gray"/>

在布局之后设置分隔线。

这是我在经过多次尝试后得出的解决方案(虽然我使用Java代码创建了视图,因为我需要动态添加它们)。但实际的Android代码不起作用,这真是遗憾。本来可以更加优雅的。 - Jamstruth
为什么不通过代码动态添加此视图?您可以创建一个线性布局,然后在该线性布局后立即添加此视图。这对您来说不是解决方案吗? - Stefano Munarini

0
尝试使用shape ="rectangle"而不是line
<shape
    android:shape="rectangle">

    <size android:height="1px" />
    <solid android:color="@color/white" />

</shape>

-3

你必须将分隔符设置到listView上,而不是LinearLayout上


1
这里没有ListView,只有一个LinearLayout。据我所知,当我编写这段代码时,如果使用ListView,它无法实现我想要的功能。这个LinearLayout包含了一系列其他的LinearLayout,其中包含了所有我需要的有用小部件等等。当我查找ListView的信息时,发现它只能包含一个没有子项的View。LinearLayout存在分隔方法。如果它们不起作用,那么它们存在的意义是什么? - Jamstruth

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