How to call getWindow() outside an Activity in Android?

后端 未结 4 444
感情败类
感情败类 2020-12-09 01:23

I am trying to organize my code and move repetitive functions to a single class. This line of code works fine inside a class that extends activity:

getWindow         


        
相关标签:
4条回答
  • 2020-12-09 01:42

    You can use following method to cast current context to activity:

    /**
     * Get activity instance from desired context.
     */
    public static Activity getActivity(Context context) {
        if (context == null) return null;
        if (context instanceof Activity) return (Activity) context;
        if (context instanceof ContextWrapper) return getActivity(((ContextWrapper)context).getBaseContext());
        return null;
    }
    

    Then you can get window from the activity.

    0 讨论(0)
  • 2020-12-09 01:49

    Pass a reference of the activity when you create the class, and when calling relevant methods and use it.

    void someMethodThatUsesActivity(Activity myActivityReference) {
        myActivityReference.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }
    
    0 讨论(0)
  • 2020-12-09 01:53

    Use

    getActivity().getWindow().requestFeature(Window.FEATURE_PROGRESS);
    

    It's will be easier

    0 讨论(0)
  • 2020-12-09 01:58

    You shall not keep references around as suggested in the accepted answer. This works, but may cause memory leaks.

    Use this instead from your view:

    ((Activity) getContext()).getWindow()...
    

    You have a managed reference to your activity in your view, which you can retrieve using getContext(). Cast it to Activity and use any methods from the activity, such as getWindow().

    0 讨论(0)
提交回复
热议问题