Reputation: 477
I have a LinearLayout
, I set the width to match_parent
. How can I match the height to the width to get a square layout?
<LinearLayout
android:id="@+id/linearLayout"
android:orientation="horizontal"
android:layout_margin="20dp"
android:layout_width="match_parent"
android:layout_height="2dp"
android:gravity="center"
android:background="@drawable/card_layout">
</LinearLayout>
Upvotes: 0
Views: 697
Reputation: 8224
To achive this you need to get width of your @+id/linearLayout
programatically
LinearLayout mLinearLayout=(LinearLayout)findViewById(R.id.linearLayout);
int screenWidth = mContext.getResources().getDisplayMetrics().widthPixels;
int screenHeight = mContext.getResources().getDisplayMetrics().widthPixels;
mLinearLayout.measure(screenWidth, screenHeight);
int layoutWidth = mLinearLayout.getMeasuredWidth();
And then set width values as height
ViewGroup.LayoutParams params = mLinearLayout.getLayoutParams();
params.height = layoutWidth;
mLinearLayout.setLayoutParams(params);
You can also do this like @balaji koduri showed in OnGlobalLayoutListener
Upvotes: 2
Reputation: 847
Make your custom layout with overrided onMeasure
@Override
protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, widthMeasureSpec);
}
Upvotes: 0
Reputation: 3703
Do it programmatically -
LinearLayout mLinearLayout=(LinearLayout)findViewById(R.id.linearLayout);
ViewGroup.LayoutParams params = mDialogLayout.getLayoutParams();
params.width = mContext.getResources().getDisplayMetrics().widthPixels;
params.height = mContext.getResources().getDisplayMetrics().widthPixels;
if you want other size -
params.width = 200;
params.height = 200;
Upvotes: 0
Reputation: 1321
try this:
final LinearLayout layout = (LinearLayout) findViewById(R.id.linearLayout);
layout.getViewTreeObserver().addOnGlobalLayoutListener(
new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
LayoutParams params = (LayoutParams) layout
.getLayoutParams();
params.height = params.width;
layout.setLayoutParams(params);
layout.getViewTreeObserver().addOnGlobalLayoutListener(
null);
}
});
Upvotes: 0