isAttachedToWindow() returns 错误

isAttachedToWindow() returns false

谁能解释为什么 isAttachedToWindow()false 而不是 true?我似乎有附件问题。

据我了解,setContentView(rl) 应该将 RelativeLayout 附加到 window。我错过了什么?

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

我的 猜测 是您不能依赖视图实际附加到 onCreate() 中的 window。您最好在 onStart()

之后进行 isAttached() 检查

根据 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.

因此,一旦调用 on start,就会向用户显示 activity,这意味着可以安全地假设您的视图已附加到 window。相反,onCreate() 可能已被调用,但 activity 可能尚未显示给用户 - 因此您的视图可能未附加。

当您执行与视图相关的操作时,该更改实际上不会立即执行,而是会在 MessageQueue of the main thread and later those messages would be handled by the Looper 的下一个循环事件中发布。

说个具体的例子吧。假设您有一个 TextViewwrap_content/wrap_content 布局属性。



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


对于您的情况,如果您等待足够多,您会看到它最终被附加。您可以通过 View#addOnAttachStateChangeListener() API.

收到有关附加状态更改的通知