java 获取页面适配器内的屏幕尺寸?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14267582/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 15:41:45  来源:igfitidea点击:

Get screen dimensions inside page adapter?

javaandroidscreen

提问by lisovaccaro

I'm trying to get screen dimensions inside page adapter. I could get it inside MainActivityand pass it to the adapter but it would be better to get it there. How can I do it, either directly inside the adapter or inside instantiateItem?

我正在尝试获取页面适配器内的屏幕尺寸。我可以把它放进去MainActivity并将它传递给适配器,但最好把它放在那里。我该怎么做,直接在适配器内部还是在内部instantiateItem

This is my code:

这是我的代码:

public class MyPagerAdapter extends PagerAdapter {
    Display display = getWindowManager().getDefaultDisplay(); // The method getWindowManager() is undefined for the type MyPagerAdapter
    display.getSize(size);
    ...
    }

回答by Olaf Dietsche

You're almost there. You already have a context. With that you can retrieve a WindowManagervia getSystemService(WINDOW_SERVICE)

你快到了。你已经有一个context. 有了它,你可以检索一个WindowManager通过getSystemService(WINDOW_SERVICE)

WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();

回答by syklon

From any context reference (such as in your intantiateItem), you can get a reference to the DisplayMetricsclass by doing

从任何上下文引用(例如在您的intantiateItem)中,您可以DisplayMetrics通过执行

context.getResources().getDisplayMetrics()

context.getResources().getDisplayMetrics()

Which gives you a reference to the DisplayMetricsclass DisplayMetrics

它为您提供了对DisplayMetricsDisplayMetrics的引用

Particularly of use to you will be the widthPixelsand heightPixelsattributes of this, which return the raw pixel height and width for the device.

对您特别有用的是它的widthPixelsheightPixels属性,它返回设备的原始像素高度和宽度。

回答by Aida Drogan

public class MyPagerAdapter extends PagerAdapter {
    DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
    int pxWidth = displayMetrics.widthPixels;
    float dpWidth = pxWidth / displayMetrics.density;
    int pxHeight = displayMetrics.heightPixels;
    float dpHeight = pxHeight / displayMetrics.density;
}

回答by Null Pointer Exception

you can Do this with WindowManager

你可以用 WindowManager 做到这一点

WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();