从活动类中获取屏幕大小

时间:2016-11-16 10:26:18

标签: java android android-studio

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

4 个答案:

答案 0 :(得分:1)

使用class Program { static void Wait(int sec) { Task.Delay(TimeSpan.FromSeconds(sec)).Wait(); } static void printQn() { Questions mcq = new Questions(); Random gen = new Random(); //prints question 1 int optionCount = 1; int x = gen.Next(5); Console.WriteLine(mcq.questions[x]); Wait(2); mcq.questionsBool[x] = true; //prints options while (optionCount < 5) { int y = gen.Next(4); if (mcq.optionsBool[x, y] == true) { int z = gen.Next(4); Console.WriteLine("[" + optionCount + "]" + mcq.options[x, z]); mcq.optionsBool[x, z] = true; Wait(1); optionCount++; } else if (mcq.optionsBool[x,y] == false) { Console.WriteLine("[" + optionCount + "]" + mcq.options[x, y]); mcq.optionsBool[x, y] = true; Wait(1); optionCount++; } } } static void Main(string[] args) { printQn(); Console.ReadKey(); } class Questions { public string[] questions = {"Who was the first Queen of England?", "What is the biggest island on Earth?", "How many Grand Slam singles titles has Roger Federer won? ", "When was the Euro introduced as legal currency on the world market? ", "What year was the first Harry Potter movie released?" }; public bool[] questionsBool = {false,false,false,false,false}; public string[,] options = { { "Queen Elizabeth I","Queen Mary I","Queen Anne" ,"Queen Matilda", }, { "Hawaii" ,"Singapore" ,"Greenland" ,"Luzon ", }, { "19" ,"17" ,"14" ,"15" , }, { "Jan 1 1999" ,"Feb 1 1999" ,"Feb 13 1999","Feb 7 1998" , }, { "2002" ,"1999" ,"2001" ,"2003" }}; public bool[,] optionsBool = { {false, false, false, false }, {false, false, false, false }, {false, false, false, false }, {false, false, false, false }, {false, false, false, false } }; } } }

DisplayMatrics

也可以获得宽度和高度像素,如下所示

    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);

答案 1 :(得分:0)

使用WindowManager

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

答案 2 :(得分:0)

将上下文传递给自定义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;
    }
}

答案 3 :(得分:0)

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