Search code examples
androidsizerowchildrenandroid-tablelayout

Table Row Child Count Based on Screen Size


I have Cards that are 100dp width and 120dp height and when the app starts I add 3 cards to each table row (I create number of table rows based on total number of cards I want to add). On phone this looks fine however on tablets theres a lot of open space because the number of children per row (in this case 3) is not dynamic to fill the available screen space. Stretching the columns of course only makes the cards wider (which imo looks very awkward). Is there a way I can simply add my cards to the layout and have it automatically determine columns/row child count based on screen size?


Solution

  • you can get the screen size using window manager

    WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
    final DisplayMetrics displayMetrics = new DisplayMetrics();
    wm.getDefaultDisplay().getMetrics(displayMetrics);
    int height = displayMetrics.heightPixels;
    int width = displayMetrics.widthPixels;
    

    or

    Display display = getWindowManager().getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);
    int width = size.x;
    int height = size.y;
    

    to find the required number of cards to load.

    better you set the width of a card as proportional to screen width for example

    int padding = 5;
    float cardwidth = width*0.25 - padding; // card with 25% width of screen   
    
          int count = width /cardwidth ; //