Get screen dimensions in pixels

2018-12-30 23:54发布

I created some custom elements, and I want to programmatically place them to the upper right corner (n pixels from the top edge and m pixels from the right edge). Therefore I need to get the screen width and screen height and then set position:

int px = screenWidth - m;
int py = screenHeight - n;

How do I get screenWidth and screenHeight in the main Activity?

30条回答
笑指拈花
2楼-- · 2018-12-31 00:09

First get view (eg. by findViewById()) and then you can use getWidth() on the view itself.

查看更多
墨雨无痕
3楼-- · 2018-12-31 00:10

Find width and height of the screen:

width = getWindowManager().getDefaultDisplay().getWidth();
height = getWindowManager().getDefaultDisplay().getHeight();

Using this, we can get the latest and above SDK 13.

// New width and height
int version = android.os.Build.VERSION.SDK_INT;
Log.i("", " name == "+ version);
Display display = getWindowManager().getDefaultDisplay();
int width;
if (version >= 13) {
    Point size = new Point();
    display.getSize(size);
    width = size.x;
    Log.i("width", "if =>" +width);
}
else {
    width = display.getWidth();
    Log.i("width", "else =>" +width);
}
查看更多
荒废的爱情
4楼-- · 2018-12-31 00:11

Simplest way:

 int screenHeight = getResources().getDisplayMetrics().heightPixels;
 int screenWidth = getResources().getDisplayMetrics().widthPixels; 
查看更多
人间绝色
5楼-- · 2018-12-31 00:11

For dynamically scaling using XML there is an attribute called "android:layout_weight"

The below example, modified from synic's response on this thread, shows a button that takes up 75% of the screen (weight = .25) and a text view taking up the remaining 25% of the screen (weight = .75).

<LinearLayout android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <Button android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight=".25"
        android:text="somebutton">

    <TextView android:layout_width="fill_parent"
        android:layout_height="Wrap_content"
        android:layout_weight=".75">
</LinearLayout>
查看更多
大哥的爱人
6楼-- · 2018-12-31 00:11

You can do get the height size using :

getResources().getDisplayMetrics().heightPixels;

and the width size using

getResources().getDisplayMetrics().widthPixels; 
查看更多
十年一品温如言
7楼-- · 2018-12-31 00:13

This is not an answer for the OP, as he wanted the display dimensions in real pixels. I wanted the dimensions in "device-independent-pixels", and putting together answers from here https://stackoverflow.com/a/17880012/253938 and here https://stackoverflow.com/a/6656774/253938 I came up with this:

    DisplayMetrics displayMetrics = Resources.getSystem().getDisplayMetrics();
    int dpHeight = (int)(displayMetrics.heightPixels / displayMetrics.density + 0.5);
    int dpWidth = (int)(displayMetrics.widthPixels / displayMetrics.density + 0.5);
查看更多
登录 后发表回答