我在协调器布局中有5个选项卡布局。
我想只在第一个标签上显示fab图标,然后隐藏在其余标签上。
我试过这个和它的工作:
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
switch (position) {
case 0:
fab.show();
break;
default:
fab.hide();
break;
}
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
问题是我还想要fab按钮的hide on scrolling
效果。
所以我创建了一个ScrollAwareFABBehavior类,它扩展了FloatingActionButton.Behavior并将CoordinatorLayout行为关联到Floating Action Button
package com.simha.yatras;
import android.content.Context;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.view.View;
public class ScrollAwareFABBehavior extends FloatingActionButton.Behavior {
public ScrollAwareFABBehavior(Context context, AttributeSet attrs) {
super();
}
@Override
public boolean onStartNestedScroll(final CoordinatorLayout coordinatorLayout, final FloatingActionButton child,
final View directTargetChild, final View target, final int nestedScrollAxes) {
// Ensure we react to vertical scrolling
return nestedScrollAxes == ViewCompat.SCROLL_AXIS_VERTICAL
|| super.onStartNestedScroll(coordinatorLayout, child, directTargetChild, target, nestedScrollAxes);
}
@Override
public void onNestedScroll(final CoordinatorLayout coordinatorLayout, final FloatingActionButton child,
final View target, final int dxConsumed, final int dyConsumed,
final int dxUnconsumed, final int dyUnconsumed) {
super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed);
if (dyConsumed > 0 && child.getVisibility() == View.VISIBLE) {
// User scrolled down and the FAB is currently visible -> hide the FAB
child.hide();
} else if (dyConsumed < 0 && child.getVisibility() != View.VISIBLE) {
// User scrolled up and the FAB is currently not visible -> show the FAB
child.show();
}
}
}
并通过
实施<android.support.design.widget.FloatingActionButton
.
.
app:layout_behavior="com.simha.yatras.ScrollAwareFABBehavior"/>
如果我从第一个标签看到任何标签,图标就会消失。 (这就是我想要的)。但是如果我滚动那个标签内部,如果我在顶部,则图标可见,到达底部时消失。
它出现在所有标签中。
ScrollAwareFABBehavior正在对所有标签执行操作。如何限制它仅在第一个选项卡上起作用。
答案 0 :(得分:0)
我明白了。我最近在stackoverflow上找到了解决方案。 Android - FAB to hide when navigating between different fragments in a viewpager
在MainActivity中将viewPager添加为静态,然后在滚动行为中添加
if (MainActivity.viewPager.getCurrentItem() == 0) {
if (dyConsunmed > 0 && child.getVisibility() == View.VISIBLE ) {
child.hide();
} else if (dyConsunmed < 0 && child.getVisibility() != View.VISIBLE) {
child.show();
}
}