views:

202

answers:

1

I can't find a way to obtain a reference the Window containing an arbitrary View v. I found getWindowToken, but I can't figure out how to use it? Does anyone know how?

Also, does anyone know why it returns an IBinder rather than a Window?

+3  A: 

Well... since all views have a reference of the activity that created them (Context), you can use that Context to get a reference of the window. Let me show you this example I wrote some minutes ago:

// main activity
import android.app.Activity;
import android.os.Bundle;
public class GetWindow extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MyView view = new MyView(this);
        view.changeSomethingInWindow(); // keep an eye on this method
        setContentView(view);
    }
}

Then, inside your view you can do this:

// your view :D
import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

public class MyView extends View{
    private Context mContext;
    public MyView(Context context) {
        super(context);
        mContext = context;
    }

    public void changeSomethingInWindow(){
        // get a reference of the activity
        Activity parent = (Activity)mContext;
        // using the activity, get Window reference
        Window window = parent.getWindow();
        // using the reference of the window, do whatever you want :D
        window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }
}

In this case, I change the mode the Window is displayed to Fullscreen. Hope this help you. Tell me if you get in trouble with this.

Cristian
Thank you for your answer. Using getWindow and casting to an activity was a good idea. I don't suppose you know why an `IBinder` is returned rather than a `Window`?
Casebash
Hello Casidiablo, there is a problem with your Code. This is only possible for views you create in your own code in a way that the context you use in your custom constructor is an activity. I tried the getContext Method of an Item from a ListAdapter and in this case I get a Context not an Activity. Activity is a subclass from Context this means you can get a Context object that could not be casted into an Activity. My test code ended in a ClassCastException.
Janusz