检查screenSize无法正常工作

时间:2016-01-25 09:25:25

标签: android screen-size

这是我检查屏幕尺寸和更改FrameLayout尺寸的代码。

    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));

我不知道为什么它不起作用。

3 个答案:

答案 0 :(得分:1)

您可以使用DisplayMetrics

  

描述有关显示的一般信息的结构,例如   它的大小,密度和字体缩放。

   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

现在您可以简单地使用screenInches逻辑。

答案 1 :(得分:0)

DisplayMetrics displaymetrics = new DisplayMetrics();
((Activity)mContext)getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int height = displaymetrics.heightPixels;
int width = displaymetrics.widthPixels;

答案 2 :(得分:0)

要更改布局参数,您必须执行此操作:

topLayout.getLayoutParams().width = 100;
topLayout.getLayoutParams().height = 100;