Android - 在视图页面中的不同片段之间导航时隐藏的 FAB

2023-12-19

我正在尝试做一些非常简单的事情。

我希望 FAB 仅出现在 TabLayout 中的一个选项卡上,并在导航到另一选项卡时隐藏。例如,一个选项卡允许您在 FAB 中添加新项目,但下一个选项卡不允许您添加项目。

我遵循“典型”XML 设计布局:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/container"
    xmlns:tools="http://schemas.android.com/tools"
    >

<android.support.design.widget.AppBarLayout
    android:id="@+id/appBarLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:minHeight="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_scrollFlags="scroll|enterAlways">

        <LinearLayout
            android:id="@+id/search_container"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center_vertical"
            android:orientation="horizontal">

            <EditText
                android:id="@+id/search_view"
                android:layout_width="0dp"
                android:layout_height="?attr/actionBarSize"
                android:layout_weight="1"
                android:background="@android:color/transparent"
                android:gravity="center_vertical"
                android:hint="Search"
                android:imeOptions="actionSearch"
                android:inputType="text"
                android:maxLines="1"
                android:paddingLeft="2dp"
                android:singleLine="true"
                android:textColor="#ffffff"
                android:textColorHint="#b3ffffff" />

            <ImageView
                android:id="@+id/search_clear"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:paddingLeft="16dp"
                android:paddingRight="16dp"
                android:src="@drawable/ic_action_cancel" />

        </LinearLayout>

    </android.support.v7.widget.Toolbar>

    <android.support.design.widget.TabLayout
        android:id="@+id/sliding_tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        app:tabMode="scrollable"
        />


</android.support.design.widget.AppBarLayout>

<android.support.v4.view.ViewPager
    android:id="@+id/viewPager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="com.example.simon.behaviours.PatchedScrollingViewBehavior"/>

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    app:borderWidth="0dp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/ic_action_new"
    android:layout_margin="16dp"
    android:layout_gravity="bottom|right"
    app:layout_anchor="@+id/viewPager"
    app:layout_anchorGravity="bottom|right|end"
    app:layout_behavior="com.example.simon.behaviours.ScrollingFABBehavior"
    android:visibility="gone"
    app:fabSize="normal">
</android.support.design.widget.FloatingActionButton>

</android.support.design.widget.CoordinatorLayout>

我对 FAB 使用了以下行为。这会导致任何向上滚动都会导致 FAB 消失,并在向下滚动时返回到屏幕上:

public class ScrollingFABBehavior extends FloatingActionButton.Behavior {
    private int toolbarHeight;

    public ScrollingFABBehavior(Context context, AttributeSet attrs) {
        super();
        this.toolbarHeight = getToolbarHeight(context);
    }

    @Override
    public boolean layoutDependsOn(CoordinatorLayout parent, FloatingActionButton fab, View dependency) {
        return super.layoutDependsOn(parent, fab, dependency) || (dependency instanceof AppBarLayout);
    }

    @Override
    public boolean onDependentViewChanged(CoordinatorLayout parent, FloatingActionButton fab, View dependency) {
        boolean returnValue = super.onDependentViewChanged(parent, fab, dependency);
        if (dependency instanceof AppBarLayout) {
            CoordinatorLayout.LayoutParams lp = (CoordinatorLayout.LayoutParams) fab.getLayoutParams();
            int fabBottomMargin = lp.bottomMargin;
            int distanceToScroll = fab.getHeight() + fabBottomMargin;
            float ratio = (float)dependency.getY()/(float)toolbarHeight;
            fab.setTranslationY(-distanceToScroll * ratio);
        }
        return returnValue;
    }

    public static int getToolbarHeight(Context context) {
        final TypedArray styledAttributes = context.getTheme().obtainStyledAttributes(
                new int[]{R.attr.actionBarSize});
        int toolbarHeight = (int) styledAttributes.getDimension(0, 0);
        styledAttributes.recycle();

        return toolbarHeight;
    }
}

我添加了一个viewpager addOnPageChangeListener:

viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        if (position == 0) {
            FloatingActionButton floatingActionButton = (FloatingActionButton) findViewById(R.id.fab);
            floatingActionButton.setVisibility(View.VISIBLE);
        }
        else
        {
            FloatingActionButton floatingActionButton = (FloatingActionButton) findViewById(R.id.fab);
            floatingActionButton.setVisibility(View.GONE);
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
});

我只希望 FAB 出现在第一页上并消失在所有其他页面上。

该代码有效,但是当我向下滑动下一页时,即使可见性设置为消失,FAB 也会出现。我认为这与FAB 的行为设置有关。有谁知道如果可见性设置为消失,为什么 FAB 在向下滑动时仍然可见?


这最终并没有成为我想要在我的应用程序中实现的东西,但我最终设法找到了答案,通过查看他们如何在 WordPress 应用程序上实现相同的东西来提供一些帮助。

在 WordPress 应用程序中,我们在应用程序的第一页上看到一个浮动操作按钮,如果您滑动到 viewpager 上的任何其他页面,该按钮就会消失:

他们通过以下代码做到了这一点 - 这是保存 viewpager 的 Activity 的代码。您可以在 onPageScrolled 方法下看到代码的相关部分,其中包含每次页面滚动时发布事件的事件总线。该事件仅包含一个名为positionOffset的变量,它是一个从0到1的整数值。如果您滚动并且页面位于两个viewpager之间的一半,则positionOffset为0.5,您就会明白:

WPMainActivity.java

mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                AppPrefs.setMainTabIndex(position);

                switch (position) {
                    case WPMainTabAdapter.TAB_NOTIFS:
                        new UpdateLastSeenTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                        break;
                }
                trackLastVisibleTab(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                // noop
            }

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                // fire event if the "My Site" page is being scrolled so the fragment can
                // animate its fab to match
                if (position == WPMainTabAdapter.TAB_MY_SITE) {
                    EventBus.getDefault().post(new MainViewPagerScrolled(positionOffset));
                }
            }
        });

该事件在包含以下代码的片段中被拾取。该事件将触发 TranslationY 方法,该方法会在页面滚动时根据页面滚动出视图的距离(由positionOffset确定)垂直动画 FAB:

我的网站片段

/*
 * animate the fab as the users scrolls the "My Site" page in the main activity's ViewPager
 */
@SuppressWarnings("unused")
public void onEventMainThread(CoreEvents.MainViewPagerScrolled event) {
    mFabView.setTranslationY(mFabTargetYTranslation * event.mXOffset);
}

最后,在布局中my_site_fragment.xml向您展示 FAB 实际上被放置到片段 xml 中而不是活动 xml 中。

<!-- this coordinator is only here due to https://code.google.com/p/android/issues/detail?id=175330 -->
<android.support.design.widget.CoordinatorLayout
    android:id="@+id/coordinator"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="end|bottom"
        android:layout_marginBottom="@dimen/fab_margin"
        android:layout_marginRight="@dimen/fab_margin"
        android:src="@drawable/gridicon_create_light"
        app:borderWidth="0dp"
        app:rippleColor="@color/fab_pressed" />
</android.support.design.widget.CoordinatorLayout>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Android - 在视图页面中的不同片段之间导航时隐藏的 FAB 的相关文章

随机推荐

  • 在编码的 ui 测试中传递命令行参数

    是否可以在编码的 ui 测试中传递命令行参数 在普通的 C 程序中 我们只需将参数与 exe 文件一起传递 例如 命令提示符中的 filename exe 2 7 但是这样的事情可以在编码的 ui 测试中完成吗 Thanks 不 你可以这样
  • ViewPager 中的可滚动 TextView

    我有一个TextView里面一个Fragment in a ViewPager我想把文字放在TextView可滚动 由于某种原因 这不起作用并且文本视图不滚动 这是我尝试过的 片段中的代码 public View onCreateView
  • PKPaymentAuthorizationViewController 不为零但未显示

    我试图显示一个 PKPaymentAuthorizationViewController 它不为零但没有显示 我以前工作过 但现在不再工作了 权利和商家 ID 看起来不错 这是我的初始化代码 没有无用的代码 PKPaymentRequest
  • 更改键盘快捷键以注释 Spyder 中的行[关闭]

    Closed 这个问题不符合堆栈溢出指南 help closed questions 目前不接受答案 我最近开始使用 Spyder IDE Python 3 6 但在习惯键盘快捷键方面遇到了一些困难 由于我使用 azerty 键盘 这很复杂
  • 使用 Kendo UI 数据源的授权标头拦截器

    我正在使用 Web api 并限制 Web api 通过令牌进行身份验证 因此为了填充数据源 我在数据源中使用请求标头 var abcDatasource new kendo data DataSource transport read u
  • .animate() - 旧版 jquery 版本 (Drupal) 冲突的队列模拟

    我正在寻找一个解决方案来推出 jquery 版本 Drupal 本身就包含该版本 它是旧版本 实际上没有任何问题 但有一个 D 我使用队列为 false 的 animate 函数 并且没有此属性 因为此属性在 jquery 1 7 中添加到
  • NSJSONSerialization 拆箱 NSNumber?

    我在用着NSJSONSerialization转动一个JSON将文档转换为核心基础类型 我的领域里有一个JSON这是一个 数字 有时是整数 有时是浮点数 现在 问题是何时NSJSONSerialization变成我的JSON进入一个NSDi
  • Git:存储但不拉取较少的文件

    我最近开始使用 LESS 当我对 Jenkins 和 Grunt 等自动化构建器进行一些研究时 似乎一个常见的建议是不要将 LESS 文件存储在存储库上 或者不要将它们放在实时服务器上 只是编译的 CSS 所以我希望能得到一些关于这方面的建
  • 使用 Javascript 更改页面

    我构建了一个 Phonegap 应用程序 我有 7 8 个页面 我需要使用 Javascript 在它们之间导航 我尝试过使用window open and window location但那些不起作用 如何使用 Javascript 更改
  • Intellisense 将 .c 文件视为 .cpp

    我正在使用 VS2010 进行 C 项目 我不断收到 Intellisense 错误IntelliSense a value of type void cannot be assigned to an entity of type Blah
  • 在 Eclipse“运行方式 -> Android 应用程序”构建中包含 Maven 依赖项

    我使用eclipse开发一个Android应用程序 Android 开发工具 ADT 插件 http developer android com guide developing eclipse adt html和maven android
  • 在 C# 中向通用列表的 FindAll 添加参数

    我有一个要通过整数参数过滤的对象列表 List
  • 如何更改引导导航菜单颜色?

    我想更改 主页 旋转 社交媒体 的颜色 但不知道如何更改 我花了几天时间弄清楚如何更改导航背景 但对颜色一无所知 因为我只想将灰色更改为白色并更改悬停颜色 我可以将颜色更改为白色 但悬停颜色将被忽略 有没有一种预期的方法来做到这一点 这是我
  • 如果条件失败,Laravel 会从模型中抛出错误

    我正在模型中进行所有验证 我的规则是 public static rules array VehicleNumber gt required unique vehicle NumberSeats gt required VehicleTyp
  • 使用 AVMutableVideoComposition 导出时出现视频方向问题

    这是我用来导出视频的功能 void videoOutput 1 Early exit if there s no video file selected if self videoAsset UIAlertView alert UIAler
  • 声纳 C# 生态系统:fxcop 错误代码 521

    在构建 NET C 解决方案时 有以下日志 fxcop 配置中的详细开关 当单独执行 fxcopcmd exe 命令时 它工作得很好 为什么它不能与 sonar runner bat 一起使用 15 Sep 2011 03 05 37 DE
  • Pandas unstack 不起作用

    最初 我的 DF 包含 1 列使用 DatetimeIndex 索引的操作 In 371 dates 2013 12 29 19 21 00 action1 2013 12 29 19 21 01 action2 2013 12 29 19
  • MySQL PHP - 选择哪里 id = array()? [复制]

    这个问题在这里已经有答案了 可能的重复 MySQL 使用数组进行查询 https stackoverflow com questions 1101662 mysql query using an array 将数组传递给 mysql htt
  • 如何将 ActiveX 与 ASP.NET 结合使用

    我创建了一个 ActiveX 组件 但无法在 ASP NET 中访问该 ActiveX 组件 使用 JavaScript 创建 ActiveX 对象时 它给出 Microsoft JScript 运行时错误 自动化服务器无法创建对象 错误消
  • Android - 在视图页面中的不同片段之间导航时隐藏的 FAB

    我正在尝试做一些非常简单的事情 我希望 FAB 仅出现在 TabLayout 中的一个选项卡上 并在导航到另一选项卡时隐藏 例如 一个选项卡允许您在 FAB 中添加新项目 但下一个选项卡不允许您添加项目 我遵循 典型 XML 设计布局