[英]Custom CoordinatorLayout behavior
這是我的布局:
<android.support.design.widget.CoordinatorLayout
android:id="@+id/coordinator_layout"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<include layout="@layout/view_product_details"/> // This contains a NestedScrollView
<LinearLayout android:id="@+id/indicator"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="right|bottom"
android:layout_marginBottom="16dp"
android:gravity="right|bottom"
android:orientation="horizontal"
app:layout_behavior="utils.CustomBehavior">
// Some views..
</LinearLayout>
我希望當用戶打開Activity時顯示指示器布局,但是當用戶向下滾動時它應該隱藏。
當用戶滾動回頁面頂部時,我希望它再次顯示。
所以我寫了一個自定義行為類:
public class CustomBehavior extends CoordinatorLayout.Behavior {
private int totalY;
public CustomBehavior(Context context, AttributeSet attrs) {
super();
}
@Override
public boolean layoutDependsOn(CoordinatorLayout parent, View child, View dependency) {
return dependency instanceof NestedScrollView;
}
@Override
public boolean onStartNestedScroll(CoordinatorLayout coordinatorLayout, View child, View directTargetChild, View target, int nestedScrollAxes) {
return nestedScrollAxes == ViewCompat.SCROLL_AXIS_VERTICAL || super.onStartNestedScroll(coordinatorLayout, child, directTargetChild, target, nestedScrollAxes);
}
@Override
public void onNestedScroll(CoordinatorLayout coordinatorLayout, View child, View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed) {
super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed);
totalY += dyConsumed;
Log.d("Scroll", "Total Y : " + totalY);
LinearLayout fabMenu = (LinearLayout) child;
FloatingActionButton wishListButton = (FloatingActionButton) fabMenu.findViewById(R.id.fab_wishlist);
FloatingActionButton collectionButton = (FloatingActionButton) fabMenu.findViewById(R.id.fab_collection);
FloatingActionButton tastedButton = (FloatingActionButton) fabMenu.findViewById(R.id.fab_tasted_list);
if (totalY > 10) {
wishListButton.hide(true);
collectionButton.hide(true);
tastedButton.hide(true);
} else if (totalY < 10) {
wishListButton.show(true);
collectionButton.show(true);
tastedButton.show(true);
}
}
}
但是總Y值的加減是不可靠的。
如何檢測用戶是否已到達NestedScrollView的頂部?
或者有更好的方法來實現這樣的東西? 謝謝!
看看以下內容是否有幫助 - 在onNestedScroll()
:
使用
if (target instanceof NestedScrollView) {
final NestedScrollView nestedScrollView = (NestedScrollView) target;
totalY = nestedScrollView.getScrollY();
}
代替
totalY += dyConsumed;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.