0

I need to group views in sections on activities and describe sections by headers, so I created custom view like below:

public class Section extends LinearLayout {
    public Section(Context context) {
        this(context, null);
    }

    public Section(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.Section, 0, 0);
        String title = a.getString(R.styleable.Section_textHeader);
        a.recycle();
        setOrientation(LinearLayout.VERTICAL);
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflater.inflate(R.layout.section_header, this, true);
        TextView titleTextView = (TextView) getChildAt(0);
        titleTextView.setText(title);
    }
}

and I use this view like below:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:custom="http://schemas.android.com/apk/res/eu.szwiec"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="8dip" >

    <eu.szwiec.Section
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        custom:textHeader="Sample Header" >

        <Button
            android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="left|center_vertical"
            android:text="go to second activity" />
    </eu.szwiec.Section>

</LinearLayout>

This solution works, but in my opinion there are 2 things to improve:

  1. LinearLayout in LinearLayout isn't optimal
  2. I have to always declare in Section android:layout_width and android:layout_height

Have You ideas for better solution of this problem? or above approach is the best?

4

1 回答 1

0

1)您不需要外部LinearLayout。只需在 xml 中的 Section 上声明填充并记住也放在xmlns:android="http://schemas.android.com/apk/res/android"那里。

2)您需要声明宽度和高度。我相信您可以使用样式,但我认为它不适合 layout_xxx 属性。

于 2013-04-14T21:25:28.660 回答