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

懵懂的女人 提交于 2019-11-27 02:02:29

问题


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().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

However it is not working when I try to include it into an external class.

How do I call getWindow() from another class to apply it inside an Activity?


回答1:


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



回答2:


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().




回答3:


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.




回答4:


Use

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

It's will be easier



来源:https://stackoverflow.com/questions/7378644/how-to-call-getwindow-outside-an-activity-in-android

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!