这是一个已知的错误,如果一个AppBarLayout包含一个可滚动视图,则滚动该视图将干扰AppBarLayout的滚动行为。
关于SO的许多答案提出了以下解决方案
CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) mAppBarLayout.getLayoutParams();
AppBarLayout.Behavior behavior = new AppBarLayout.Behavior();
behavior.setDragCallback(new AppBarLayout.Behavior.DragCallback() {
@Override
public boolean canDrag(AppBarLayout appBarLayout) {
return false;
}
});
params.setBehavior(behavior);
效果很好,除了在AppBarLayout内还有另一个可以滚动AppBarLayout的View时。
这是我的布局:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:mapbox="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:id="@+id/appBarLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:fitsSystemWindows="true">
<android.support.design.widget.CollapsingToolbarLayout
android:id="@+id/collapsingToolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
app:layout_scrollFlags="scroll|exitUntilCollapsed"
app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
<fragment
android:id="@+id/mapFragment"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_collapseMode="parallax" />
</android.support.design.widget.CollapsingToolbarLayout>
<include layout="@layout/custom_layout"
android:layout_width="match_parent"
android:layout_height="48dp"
android:background="?attr/colorAccent"/>
</android.support.design.widget.AppBarLayout>
我希望能够滚动地图(这可以通过从canDrag返回false来实现),但是当触摸custom_layout项并向上移动时,仍然能够折叠布局。
所以我需要像
behavior.setDragCallback(new AppBarLayout.Behavior.DragCallback() {
@Override
public boolean canDrag(AppBarLayout appBarLayout) {
if(mapIsScrolled)
return false;
else
return true;
}
});
任何想法如何实现这一目标?
最佳答案
将其移出AppBarLayout:
<include layout="@layout/custom_layout"
android:layout_width="match_parent"
android:layout_height="48dp"
android:background="?attr/colorAccent"/>
或者,如果您确实需要布局在上部折叠部分中,则将触摸侦听器添加到布局中(或尝试使用焦点侦听器)。
private boolean handleTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_MOVE:
canCollapse = true;
}
return false;
}
public boolean canDrag(AppBarLayout appBarLayout) {
if(canCollapse)
return true;
else
return false;
}
还没有尝试过,所以您可能还需要再做几周。