Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LinearLayout with dividers on pre Honeycomb

From API level 11 setDividerDrawable() and setShowDividers() was introduced on LinearLayout, enabling the linear layout to show dividers between child elements. I would really like to use this feature, but I am also targeting devices before Honeycomb (API level < 11).

One way to fix this is to extend LinearLayout and add the divider manually. This is a prototype:

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);
    }
}

However, using such an implementation will change the behavior of any clients iterating over the children. Some views will be the ones inserted by the client himself, some will be inserted by the DividerLinearLayout. Problems will also happen if the user is inserting views at specified indexes. One could implement a conversion of indexes, but this could lead to nasty errors if done wrong. Also, I think a lot more of the methods needs to be overridden.

Is there any better way of solving the problem? Has someone already developed a freely usable DividerLinearLayout equivalent? It does not seem to exist in the compatibility libraries for Android.

like image 271
foens Avatar asked Aug 27 '12 15:08

foens


1 Answers

If I'm not mistaken, the ActionBarSherlock library already implemented this to provide backwards compatible ActionBar tabs. You might want to include that library first and give it a whirl before rolling your own.

This is the code for the specific class (com.actionbarsherlock.internal.widget.IcsLinearLayout).

like image 195
dmon Avatar answered Oct 09 '22 20:10

dmon