我在网上搜索了这个问题的任何好的解决方案,但没有找到。所以我做了一个技巧来做到这一点。
首先我们需要请求操作栏覆盖功能。所以在你的活动的onCreate() 之前,setContntView() 调用:requestWindowFeature(com.actionbarsherlock.view.Window.FEATURE_ACTION_BAR_OVERLAY);
它将使包括导航抽屉在内的所有内容都绘制在操作栏后面。我们不需要这个,所以我们需要设置 FrameLayout 的上边距,它在 Activity 中承载我们的 Fragment,并具有操作栏的确切高度。在activity的布局文件中我们需要做如下:
<!-- Framelayout to display Fragments -->
<FrameLayout
android:id="@+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="?attr/actionBarSize" />
它只会让导航抽屉出现在操作栏后面。
现在我们将在导航抽屉打开一半时隐藏操作栏,并在抽屉接近关闭时显示它。为此,我们需要在活动中进行以下操作:
@Override
public void onDrawerSlide(View drawerView, float slideOffset) {
super.onDrawerSlide(drawerView, slideOffset);
if(slideOffset > 0.5){
actionBar.setBackgroundDrawable(null);
actionBar.hide();
} else {
actionBar.show();
if(slideOffset < 0.1){
actionBar.setBackgroundDrawable(layerDrawable);
}
}
}
如您所见,在我开始隐藏它之前,我还更改了操作栏的背景可绘制对象以使其透明,并在我将其显示回来时将其更改回我的自定义背景。
我的自定义背景是一个 layerListDrawable,它是全透明的,但底部有一个分隔线和一些阴影。
为了实现这一点,我在 XML 中定义了以下层列表:
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:top="0dp" android:left="0dp" android:bottom="0dp" android:right="0dp">
<shape android:shape="rectangle">
<solid android:color="@android:color/transparent"/>
</shape>
</item>
<item android:top="0dp" android:left="0dp" android:bottom="0dp" android:right="0dp">
<shape android:shape="rectangle">
<solid android:color="#afafaf"/>
</shape>
</item>
<item android:top="0dp" android:left="0dp" android:bottom="0dp" android:right="0dp">
<shape android:shape="rectangle">
<gradient
android:angle="270"
android:startColor="#88afafaf"
android:endColor="#33afafaf"
/>
</shape>
</item>
</layer-list>
为了从这个 XML 中获取我需要的背景,我在活动中执行以下操作:
final ActionBar actionBar = getSupportActionBar();
final LayerDrawable layerDrawable = (LayerDrawable) getResources()
.getDrawable(R.drawable.shadow_divider);
final TypedArray styledAttributes = getTheme().obtainStyledAttributes(
new int[] { R.attr.actionBarSize });
int topOffset = (int) (styledAttributes.getDimension(0, 0));
styledAttributes.recycle();
layerDrawable.setLayerInset(1, 0, topOffset - 3, 0, 2);
layerDrawable.setLayerInset(2, 0, topOffset - 2, 0, 0);
actionBar.setBackgroundDrawable(layerDrawable);
其中 R.drawable.shadow_divider 是我之前定义的 XML 层列表。
看起来真的很棒!希望它可以帮助某人。
编辑
我在这里遇到了一个小错误,有时这可能是我迷恋的原因。这是固定代码:
`
<FrameLayout
android:id="@+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
**android:paddingTop="?attr/actionBarSize"** />`
应该是 paddingTop 而不是 layout_marginTop!