Calling a non-static method from outside the class

I often have to deal with a similar error when programming in Java on Android. For example, I have a class where I set the flag.

public class ViewActivity extends Activity {  
...

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
       getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    ...
}

In another class, I want to reset FLAG_KEEP_SCREEN_ON

class DrawOnTop extends View {
...
if (condition) {
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}

but this does not work since I get the "getWindow method undefined for type DrawOnTop".

So, I'm trying to define a clearFlags method in the ViewActivity class

void clearFlags() {
    getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}

and call it from the DrawOnTop class:

    if (condition) {
        ViewActivity.clearFlags();
    }

This does not work: I get "Can't make a static reference to the non-static clearFlags () method of type ViewActivity." Well, let it be static then.

static void clearFlags() {
    getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}

and then I get "Can't make a static reference to the non-static getWindow method from type Activity"

How can I fulfill this statement?

+4
4

DrawOnTop ViewActivity, Context getWindow(). , , DawOnTop , . , !

+1

getWindow() clearFlags. clearFlags(Window window) : WindowHelper.getInstance().clearFlags(getWindow());

:

public class WindowHelper {

    public static final WindowHelper instance = new WindowHelper();

    public static WindowHelper getInstance() {
        return instance;
    }

    public void clearFlags(Window window) {
        window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }
}
0

, Aksaçlı, :

ViewActivity DrawonTop : mDrawOnTop = new DrawOnTop(this);

:

public DrawOnTop(Context context) {
            super(context);

ViewActivity.clearFlags(); ((ViewActivity)getContext()).clearFlags();

0

Perhaps you should refer to the initialized object in your static method. Therefore, instead of:

void clearFlags() {
    getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}

you must create a static instance variable of your window:

private static staticWindowInstance;

void clearFlags() {
getStaticWindowInstance().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}

For more information, you should check out the Singleton design template .

-1
source

Source: https://habr.com/ru/post/1621851/


All Articles