在Honeycomb之前如何在LinearLayout中添加分割线

5

从API级别11开始,setDividerDrawable()setShowDividers()被引入到LinearLayout中,使得线性布局能够在子元素之间显示分割线。我真的很想使用这个功能,但我也要针对蜂巢(API级别<11)之前的设备。

解决这个问题的一种方法是扩展LinearLayout并手动添加分隔符。 这是一个原型:

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;

public class DividerLinearLayout extends LinearLayout
{
    public DividerLinearLayout(Context context)
    {
        super(context);
    }

    public DividerLinearLayout(Context context, AttributeSet attrs)
    {
        super(context, attrs);
    }

    public DividerLinearLayout(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
    }

    @Override
    public void addView(View child)
    {
        if(super.getChildCount() > 0)
        {
            super.addView(LayoutInflater.from(getContext()).inflate(R.layout.divider, null));
        }
        super.addView(child);
    }
}

然而,使用这样的实现将改变任何迭代子项的客户端的行为。一些视图将是客户端自己插入的视图,一些将由DividerLinearLayout插入。如果用户在指定的索引处插入视图,则也会出现问题。可以实现索引的转换,但如果操作不当,可能会导致严重错误。此外,我认为需要覆盖更多的方法。
有没有更好的解决问题的方法?是否已经开发了可自由使用的DividerLinearLayout等效物?似乎在Android的兼容库中不存在。
2个回答

10
如果我没有错的话,ActionBarSherlock库已经实现了这个功能,以提供向后兼容的ActionBar选项卡。在自己动手之前,您可能需要先包含该库并试用一下。
这是特定类(com.actionbarsherlock.internal.widget.IcsLinearLayout)的代码。你可以查看

我已经在使用ActionBarSherlock,所以IcsLinearLayout是一个很容易的替换方案。它运行得非常好 - 感谢您指出它。 - foens
似乎在xml中使用时出现了错误。此外,您提供的链接不再有效。 - android developer

1
IcsLinearLayout是内部使用的,因为ActionBarSherlock将不再更新,建议改用Google的"LinearLayoutICS"。
阅读这里了解如何使用它。

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