Alex Alex - 5 months ago 32
Android Question

Layout weight in Gridview

I want the cards to fill the entire screen when it comes to various screen dimensions. I would like to use the weights or any other option that can do the same.


<!--Card 1-->
<android.support.v7.widget.CardView
android:id="@+id/cardView1"
android:layout_height="200sp"
android:layout_width="150sp">

</android.support.v7.widget.CardView>

<!--Card 2-->
<android.support.v7.widget.CardView
android:id="@+id/cardView2"
android:layout_height="200sp"
android:layout_width="150sp">

</android.support.v7.widget.CardView>

<!--Card 3-->
<android.support.v7.widget.CardView
android:id="@+id/cardView3"
android:layout_height="200sp"
android:layout_width="150sp">

</android.support.v7.widget.CardView>

<!--Card 4-->
<android.support.v7.widget.CardView
android:id="@+id/cardView4"
android:layout_height="200sp"
android:layout_width="150sp">

</android.support.v7.widget.CardView>
</GridLayout>


I want the 4 cards to fit the entire screen for any device type

Answer

For this you have to set the height of the gridview dynamically. In your Activity class define.

     public static int heighth;
     public static int width;
     DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);

        widthh = metrics.widthPixels;
        heighth = metrics.heightPixels;

And after this in your gridview adapter class write

gridView.setMinimumHeight((Home.heighth)/3-70);

Here Home is your Activity class Home.java. I have divided by 3 because I have only 3 rows and the subtraction of 70 is just for adjusting the view. Hope it helps!

Comments