1

Is it possible to set the width of a child to be a fixed width unless the screen is less than that width?

i.e. I want the CardView below to be 400dp normally, unless it's on a small screen at which point it should be the screen-width (minus margin)...

<cdudigital.com.conjugator.MyLinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    tools:context=".GameActivity">
    <android.support.v7.widget.CardView
        xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:id="@+id/card_view"
        android:layout_gravity="center"
        android:gravity="center"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        card_view:cardCornerRadius="4dp"
        card_view:cardElevation="3dp">
    </android.support.v7.widget.CardView>
</cdudigital.com.conjugator.MyLinearLayout>
lombrozo
  • 169
  • 3
  • 12

2 Answers2

2

Xml solution, ConstraintLoyout + children:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <androidx.cardview.widget.CardView
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintWidth_max="400dp">
</androidx.constraintlayout.widget.ConstraintLayout>

See Android using Linear layout maxWidth, not work with fill_parent Roland van der Linden response.

Prevents the child from being larger than the maximum 400dp, but may be smaller.

enter image description here

Barrrettt
  • 645
  • 7
  • 15
1

Get the DP of screen

DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
float dpWidth = displayMetrics.widthPixels / displayMetrics.density;

And check to see if it is less than 400

if(dpWidth < 400){
    cardView.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT));
} else {
    cardView.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,(400 * displayMetrics.density + 0.5f)));
}

Or in the XML

android:layout_width="match_parent"
android:maxWidth="400dp"
Chris Stillwell
  • 10,266
  • 10
  • 67
  • 77