How to get Screen metrics outside an Activity?

后端 未结 4 1650
名媛妹妹
名媛妹妹 2021-02-04 01:59

I have a Generic Pool that i am making here:

public class FruitPool extends GenericPool {
// ======================================================         


        
相关标签:
4条回答
  • 2021-02-04 02:30

    Despite the fact there is an accepted answer here, I'm posting another answer. The reasoning for this is the following. Passing contexts is not always a good idea imho, because in some cases (such as applied libraries, for example) contexts should not build additional and unnecessary dependencies from an application. The code is simple:

    DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics();
    

    It provides a solution for cases when known limitations of this method are not important for a developer. According to Android documentation:

    getSystem() returns a global shared Resources object that provides access to only system resources (no application resources), and is not configured for the current screen (can not use dimension units, does not change based on orientation, etc).

    Anyway, all fields of DisplayMetrics are filled in with meaningful information. In my case, it was DPI which I was after. And the method provides me with DPI without a context.

    0 讨论(0)
  • 2021-02-04 02:31

    Here's another way to get the display metrics that is configured for the current screen.

    final DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();

    0 讨论(0)
  • 2021-02-04 02:43

    The simplest thing would be to pass a Context to the FruitPool constructor. It could then retrieve the display metrics by calling Context.getWindowManager(). (If you want to run that code outside the constructor, save context.getApplicationContext(), in case it was passed an Activity context.)

    EDIT: If you adopt this approach and are passing an Activity to the FruitPool object, and the lifetime of the FruitPool object might exceed the lifetime of the activity, then you must not keep a reference to the activity. You should instead keep a reference to context.getApplicationContext(). Since getWindowManager() is only defined for an Activity, you can instead use this expression to obtain the WindowManager:

    (WindowManager) context.getSystemService(Context.WINDOW_SERVICE)
    
    0 讨论(0)
  • 2021-02-04 02:46

    Here is the api I have written to get the screen width, you need a context to get the window system service. Similarly you can get the height.

    int getWindowWidth() {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);
        return size.x;
    }
    
    0 讨论(0)
提交回复
热议问题