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:
- LinearLayout in LinearLayout isn't optimal
- 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?