Androidで携帯電話機の画面の幅を取得
3530 ワード
背景
プロジェクトでpopupwindowを作成する場合は、幅を設定する必要があります.この場合、携帯電話機の画面の幅を取得する必要があります.携帯電話機の画面の幅の高さに基づいて、popupwindowの幅を間接的に決定します(画面の幅の一定の割合を高くすることができます).これにより、異なる解像度の携帯電話でpopupwindowが表示される位置の大きさが同じ相対的な位置に表示される適切な効果を実現することができます.
ツールクラス
携帯電話の画面の幅を取得するには、以下のようにツールクラスに書きました.
package com.example.pc_2.squaremapviewdraw.utils;
import android.content.Context;
import android.util.DisplayMetrics;
import android.view.WindowManager;
/**
* Created by zouqi on 2018/1/15.
*/
public class ScreenUtil {
public static final String WIDTH = "width";//
public static final String HEIGHT = "height";//
private WindowManager windowManager;
private DisplayMetrics metrics = new DisplayMetrics();
public ScreenUtil(Context context) {
this.windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
}
/**
* , px
* @param s
* @return
*/
public int getScreenSize(String s) {
// ,
windowManager.getDefaultDisplay().getMetrics(metrics);
int w_or_h = 0;
switch (s){
case WIDTH://
w_or_h = metrics.widthPixels;
break;
case HEIGHT://
w_or_h = metrics.heightPixels;
break;
}
return w_or_h;//
}
}
コードは比較的簡単で、あまり説明しないで、肝心な注釈が与えられました.
プロジェクトでの使用
取得幅は次のとおりです.
int width = new ScreenUtil(getContext()).getScreenSize(ScreenUtil.WIDTH);
取得高さは次のとおりです.
int height = new ScreenUtil(getContext()).getScreenSize(ScreenUtil.HEIGHT);
========================================================================
A little bit of progress every day!Come on!