这可能不是您希望的答案.
考虑一个不同的问题:我们可以在调用setContentView(…)之后更改活动主题吗?这个问题已被多次询问,一个常见的解决方案是重新创建(调用finish()和startActivity(getIntent()))活动并在setContentView(…)之前设置新主题.
您的问题是对此的扩展 – 增加了从片段更改主题的复杂性.无论如何,我不认为上面提到的解决方案是好的.
ActionBar是创建Activity时首先要初始化的组件之一.我不认为你会找到一种方法以某种方式用新属性“刷新”它.请参阅下面的requestFeature(Window.FEATURE_ACTION_BAR_OVERLAY)方法如何处理post-setContentView(…)调用:
@Override
public boolean requestFeature(int featureId) {
if (mContentParent != null) {
throw new AndroidRuntimeException("requestFeature() must be
called before adding content");
}
....
....
}
因此,如果已经为Activity调用了setContentView(…)(在您的情况下,它),将抛出运行时异常.
您是否有可能甚至不需要此功能?
首先将ActionBar设置为主题中的叠加层:
true
true
Here’s my problem. I want the actionbar to be displayed as overlay in some fragments…
好的.我们已经为此做好了准备.
… but not in others.
假设您不希望将ActionBar作为Fragment B中的叠加层.然后,在Fragment B的布局中,执行以下操作:
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="?android:attr/actionBarSize" > <<
for compatibility
....
....
将上边距设置为ActionBar的大小,片段B看起来好像有一个常规的ActionBar – 而不是一个重叠的ActionBar.实现这一目标的另一种方法是将一个带有android的视图:layout_height =“?android:attr / actionBarSize”放置为上面布局中的第一个子节点.
在本质上:
>你的ActionBar将是一个叠加层.
>在ActionBar将自动隐藏的片段中,片段布局不会有任何上边距设置.
>在不应覆盖ActionBar的片段中,片段布局的上边距设置为actionBarSize.
值得注意的一点(感谢Jelle):
如果您的ActionBar是半透明的,最好使用填充而不是边距来获得一致的外观.