Search code examples
androiddynamicviewscreen-size

Add views dynamically depending on the screen size in Android


I want to add views dynamically (horizontal or vertical) in a row. Each view has a fixed size and fixed padding. How do I decide how many views I can add dynamically depending on the device screen size. For example, smaller phones or with mdpi might have lesser number of views added compared to xhdpi devices.

Thanks.


Solution

  • There are a number of different ways.

    First, you can check the size of your container by calling getWidth() and getHeight() In your view you can override onMeasure()

    @Override 
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
       int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
       int parentHeight = MeasureSpec.getSize(heightMeasureSpec);
    }
    

    If you have different XML layouts based on the screen size, you can check to see what one of them loaded and act accordingly.