Michael Osofsky
Michael Osofsky

Reputation: 13195

isAttachedToWindow() returns false

Can anyone explain why isAttachedToWindow() is false instead of true? I seem to be having attachment issues.

As I understood it, setContentView(rl) should attach the RelativeLayout to the window. What am I missing?

public class TestActivity extends Activity {
    protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            final RelativeLayout rl = new RelativeLayout(this);
            setContentView(rl);
            boolean isAttached = rl.isAttachedToWindow();
    }
}

Upvotes: 5

Views: 2863

Answers (2)

azizbekian
azizbekian

Reputation: 62199

When you are performing a view-related action, that change won't actually be executed immediately, rather it would be posted on the MessageQueue of the main thread and later those messages would be handled by the Looper's next loop event.

Let's speak with a concrete example. Imagine you have a TextView with wrap_content/wrap_content layout attributes.



    TextView textView = ...;
    textView.setText("some fancy text");

    // Will print `0 0`, because this message hasn't yet beet "parsed" by `Looper`
    // Changes will take effect on the next frame
    Log.i("tag", textView.getWidth() + " " + textView.getHeight());

    // Will print `some fancy text`, because this is just a plain Java object
    Log.i("tag", textView.getText());


In your case, had you waited enough you'd see it eventually being attached. You can be notified about attached state change via View#addOnAttachStateChangeListener() API.

Upvotes: 2

Tim Malseed
Tim Malseed

Reputation: 6373

My guess is you can't rely on the view to actually be attached to the window in onCreate(). You're better off doing your isAttached() check after onStart()

According to the docs for onStart():

void onStart()

Called after onCreate(Bundle) — or after onRestart() when the activity had been stopped, but is now again being displayed to the user. It will be followed by onResume().

Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.

So, once on start is called, the activity is being displayed to the user, which means it's safe to assume your views are attached to the window. Conversely, onCreate() may have been called, but the activity might not yet be displaying to the user - so your views might not be attached.

Upvotes: 1

Related Questions