requestFeature 方法的位置需要放在界面渲染方法之前,比如放在setContentView方法之前。
final boolean isCustom = requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); setContentView(R.layout.you_layout); if(isCustom){ getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_tiltebar); }
就是说,界面的属性(这里指的是window的属性)一般要在展示界面内容(setContentView)之前确定,这个也符合逻辑。然后,今天在我使用preferenceActivity时候,出错了:requestFeature() must be called before adding content。相关代码如下:
super.onCreate(savedInstanceState); final boolean isCustom = requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); addPreferencesFromResource(R.xml.preferences); if(isCustom){ getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_tiltebar); }
网上查了下,没有结果,于是我觉得是不是super.onCreate(savedInstanceState)里面有文章,进入源码一看,果然:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(com.android.internal.R.layout.preference_list_content); mPreferenceManager = onCreatePreferenceManager(); getListView().setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); }可以看出,在super.onCreate(savedInstanceState)里面就出现了活动界面内容的展示,即调用setcontentview方法。于是把requestFeature()方法放在super.onCreate(savedInstanceState)前面,就ok了