Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

android

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?

like image 945
Kalimah Avatar asked Sep 11 '11 13:09

Kalimah


People also ask

How to use getWindow in service Android?

You can't get a window in a Service. But you can use WindowManager to add a view(root) as you did already. And You can also update view through updateViewLayout, you can change your window's status(window type, flag, x, y, w, h, gravity, etc...)

How can I get current activity?

This example demonstrates How to get current activity name in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.


2 Answers

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

like image 100
Oliver Hausler Avatar answered Sep 27 '22 19:09

Oliver Hausler


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); } 
like image 33
MByD Avatar answered Sep 27 '22 21:09

MByD