如何获取当前设备屏幕的宽和高

在安卓开发中,我们有时候需要获得当前设备屏幕的宽和高来进行一些操作,比如屏幕适配。下面介绍两种方法来进行获取:

方式一:

public String getScreenSize(){
        DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
        int widthPixels = displayMetrics.widthPixels;
        int heightPixels = displayMetrics.heightPixels;
        return "屏幕的宽是:"+widthPixels+",屏幕的高是:"+heightPixels;
    }

方式二:

public String getScreenSize2(){
        Point point = new Point();
        Display defaultDisplay = getWindowManager().getDefaultDisplay();
        defaultDisplay.getSize(point);
        return "屏幕的宽是:"+point.x+",屏幕的高是:"+point.y;
    }

下面给出运行结果图,完整的代码是这样的:

public class MainActivity extends Activity {

    private TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = (TextView) findViewById(R.id.textview);
        textView.setText(getScreenSize());
        textView.setText(getScreenSize2());
    }
    public String getScreenSize(){
        DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
        int widthPixels = displayMetrics.widthPixels;
        int heightPixels = displayMetrics.heightPixels;
        return "屏幕的宽是:"+widthPixels+",屏幕的高是:"+heightPixels;
    }
    public String getScreenSize2(){
        Point point = new Point();
        Display defaultDisplay = getWindowManager().getDefaultDisplay();
        defaultDisplay.getSize(point);
        return "屏幕的宽是:"+point.x+",屏幕的高是:"+point.y;
    }
}


通过实验可以看到,两种方法的结果完全一样。好了,这篇文章就到这里!

你可能感兴趣的:(如何获取当前设备屏幕的宽和高)