Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/amazon-web-services/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 从活动类中获取屏幕大小_Java_Android_Android Studio - Fatal编程技术网

Java 从活动类中获取屏幕大小

Java 从活动类中获取屏幕大小,java,android,android-studio,Java,Android,Android Studio,我需要知道扩展ArrayAdapter类的类中的屏幕大小。我不能使用getWindowManager方法,因为我的类不扩展Activity类。我能做什么?使用WindowManager WindowManager window = (WindowManager) getSystemService(Context.WINDOW_SERVICE); Display display = window.getDefaultDisplay(); int width = display.getWidth(

我需要知道扩展ArrayAdapter类的类中的屏幕大小。我不能使用getWindowManager方法,因为我的类不扩展Activity类。我能做什么?

使用WindowManager

WindowManager window = (WindowManager) getSystemService(Context.WINDOW_SERVICE); 
Display display = window.getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight(); 

将上下文传递给自定义ArrayAdapter,然后从中获取大小

像这样:

public class TestAdapter extends ArrayAdapter<String> {
    public TestAdapter(Context context, ArrayList<String> tests) {
       super(context, 0, tests);
    }

    public void SomeMethod() {
       Context ctx = getContext();
       DisplayMetrics metrics = ctx.getResources().getDisplayMetrics();
       int width = metrics.widthPixels;
       int height = metrics.heightPixels;
    }
}
公共类TestAdapter扩展了ArrayAdapter{
公共测试适配器(上下文、ArrayList测试){
超级(上下文,0,测试);
}
公共方法(){
Context ctx=getContext();
DisplayMetrics=ctx.getResources().getDisplayMetrics();
int width=metrics.widthPixels;
int height=metrics.heightPixels;
}
}

使用
显示矩阵

    DisplayMetrics metrics = context.getResources().getDisplayMetrics();
    double x = Math.pow(metrics.widthPixels/metrics.xdpi,2);
    double y = Math.pow(metrics.heightPixels/metrics.ydpi,2);
    double screenInches = Math.sqrt(x+y);
还可以获得宽度和高度像素,如下所示

double heightpixel = metrics.heightPixels;
double widthpixel = metrics.widthPixels;

在activity类中使用getWindowManager()方法,在适配器构造函数中传递宽度和高度后获取屏幕宽度和高度,或者使用shared prefrence。

使用
DisplayMetrics
获取设备高度和宽度,然后通过类传递