从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的兼容库中不存在。
IcsLinearLayout
是一个很容易的替换方案。它运行得非常好 - 感谢您指出它。 - foens