«

关于使用RequestWindowFeature为啥一定要在setContentView之前调用

时间:2024-3-2 17:47     作者:韩俊     分类: Android


网上关于RequestWindowFeature()的用法有很多,却难找一篇解释清楚的文章供大家了解,下面这是我遇到这个问题并且得出的一点结论供大家参考。

Activity的RequestWindowFeature()实际上走的是PhoneWIndow的requestFeature(),在PhoneWIndow的requestFeature()中有个前提条件,成员属性mContentParent不能为非null,这是构建窗体的view,即在为窗体设置属性时,还不能构建窗体。如下:

@Override
public boolean requestFeature(int featureId) {
if (mContentParent != null) {
throw new AndroidRuntimeException("requestFeature() must be called before adding content");
}

.....

return super.requestFeature(featureId);
}


但是在activity中使用setContentView()时,实际上走的是phonewindow的setContentView,根据代码我们看到


@Override

public void setContentView(View view, ViewGroup.LayoutParams params) {<br />
    if (mContentParent == null) {<br />
        installDecor();<br />
    } else {<br />
        mContentParent.removeAllViews();<br />
    }<br />
    mContentParent.addView(view, params);<br />
    final Callback cb = getCallback();<br />
    if (cb != null &amp;&amp; !isDestroyed()) {<br />
        cb.onContentChanged();<br />
    }<br />

}

它会首先判断mContentParent 是否为null,如果为null,进入installDecor();

private void installDecor() {

......

if (mContentParent == null) {
mContentParent = generateLayout(mDecor);


mTitleView = (TextView)findViewById(com.android.internal.R.id.title);
if (mTitleView != null) {
if ((getLocalFeatures() & (1 << FEATURE_NO_TITLE)) != 0) {
View titleContainer = findViewById(com.android.internal.R.id.title_container);
if (titleContainer != null) {
titleContainer.setVisibility(View.GONE);
} else {
mTitleView.setVisibility(View.GONE);
}
if (mContentParent instanceof FrameLayout) {
((FrameLayout)mContentParent).setForeground(null);
}
} else {
mTitleView.setText(mTitle);
}
}

.....

}

这是installDecor方法的部分代码,从中我们可以看到,它会对mContentParent 进行初始化,从而赋予相应的值,这就是RequestWindowFeature为啥一定要在setContentView之前调用就会抛此类异常

Caused by: android.util.AndroidRuntimeException: requestFeature() must be called before adding content
10-04 15:15:36.218: E/AndroidRuntime(5176): at com.android.internal.policy.impl.PhoneWindow.requestFeature(PhoneWindow.java:181)
10-04 15:15:36.218: E/AndroidRuntime(5176): at android.app.Activity.requestWindowFeature(Activity.java:2729)
10-04 15:15:36.218: E/AndroidRuntime(5176): at com.solar.BaseActivity.onCreate(BaseActivity.java:20)
10-04 15:15:36.218: E/AndroidRuntime(5176): at com.solar.SetupInfoActivity.onCreate(SetupInfoActivity.java:53)
10-04 15:15:36.218: E/AndroidRuntime(5176): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
10-04 15:15:36.218: E/AndroidRuntime(5176): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)d

标签: android

热门推荐