Search code examples
androidscreen-size

Checking screenSize is not working


This is my code for checking screen sizes and changing the FrameLayout size.

    FrameLayout topLayout = (FrameLayout) findViewById(R.id.topLayout);

    DisplayMetrics dm = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(dm);
    double x = Math.pow(dm.widthPixels/dm.xdpi,2);
    double y = Math.pow(dm.heightPixels / dm.ydpi, 2);
    double screenInches = Math.sqrt(x + y);

    if (screenInches < 5) topLayout.setLayoutParams(new LinearLayout
    .LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,170));
    if (screenInches >= 5 && screenInches < 7) topLayout
    .setLayoutParams(new LinearLayout 
    .LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 200));
    else topLayout.setLayoutParams(new LinearLayout
    .LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 230));

I don't know why its not working.


Solution

  • You can use DisplayMetrics .

    A structure describing general information about a display, such as its size, density, and font scaling.

       DisplayMetrics metrics = getResources().getDisplayMetrics();
    
       int DeviceTotalWidth = metrics.widthPixels;
       int DeviceTotalHeight = metrics.heightPixels;
       FrameLayout topLayout = (FrameLayout) findViewById(R.id.topLayout);
    
       topLayout.getLayoutParams().height= (DeviceTotalHeight/4); // Use Your Logic
    

    Now you can use your screenInches logic simply .