Skip to content

Instantly share code, notes, and snippets.

@kakajika
Last active June 7, 2022 18:09
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kakajika/7bb9f442f08d7bbcb7dd2a3c4c89d3ad to your computer and use it in GitHub Desktop.
Save kakajika/7bb9f442f08d7bbcb7dd2a3c4c89d3ad to your computer and use it in GitHub Desktop.
Custom LinearLayout takes max measured width of all children for its width.
/**
* @author kakajika
* @since 2016/04/27
*/
public class MaxLinearLayout extends LinearLayout {
public MaxLinearLayout(Context context) {
super(context);
}
public MaxLinearLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MaxLinearLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int maxWidth = 0;
for (int i=0; i<getChildCount(); ++i) {
View child = getChildAt(i);
child.measure(
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)
);
maxWidth = Math.max(maxWidth, child.getMeasuredWidth());
}
widthMeasureSpec = MeasureSpec.makeMeasureSpec(maxWidth, MeasureSpec.getMode(widthMeasureSpec));
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
<com.labo.kaji.MaxLinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Space
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
</com.labo.kaji.MaxLinearLayout>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment