繁体   English   中英

底部导航栏应使用多少个活动?

[英]How many activities should I use with a bottom navigation bar?

我是android studio的新手,将不胜感激。

我已经在MainActivity中以编程方式设置了底部导航栏。 我想知道-与其他片段一起设置的最佳方法是什么。 我有三个片段,一个用于导航栏中的每个选项卡,其他的片段可以在从导航栏片段中按下按钮时打开。

我的问题是,在连接连接到导航栏的片段的同一活动中或在其他活动中,我应在哪里设置这些其他片段。

如何保存显示的片段的当前状态,以便当我移至其他选项卡然后向后移动时,其状态与离开时相同。

我的问题是,这些其他片段应在哪里设置? 在连接连接到导航栏的片段的同一活动中或在另一活动中。

这取决于您以及如何显示片段。 您可以在同一活动中显示它们或打开另一个活动。 但是请记住,如果打开另一个活动,则将丢失上一个活动的导航栏(一个活动始终使用整个屏幕)

FragmentManager和FragmentTransaction到底做什么?

如何保存显示的片段的当前状态,以便当我移至其他选项卡然后向后移动时,其状态将与离开时的状态相同?

https://developer.android.com/guide/components/fragments.html#Lifecycle上了解片段生命周期

具体来说,您想将状态保存在onSaveInstanceState ,并且在onCreate重新创建片段时,保存的内容将发送回给您。

我想进一步说明@rupps所说的内容,因为我觉得FragmentManager / Transaction的作用所在并没有从您期望的地方得到。

我假设您正在使用BottomNavigationView

不管Fragment的(重要)生命周期如何,您都必须了解Fragment 总是附加到活动中(请注意:这不是真的,但现在不谈论无头的片段)。

您可以采用的方法是,“活动”布局如下所示:(使用伪代码)

<RelativeLayout width=match_parent height=match_parent>
  <FrameLayout 
     id="@+id/your_fragment_container" 
     width=match_parent 
     height=match_parent
     layout_above="@+id/navbar" />
  <BottomNavigationView 
     id="@id/navbar"
     width=match_parent 
     height=wrap_content 
     align_parent_bottom=true />
</RelativeLayout>

这样,BottomNavBar将始终出现在布局的底部。

现在您需要处理片段到那里了……假设您需要在该栏上附加一个侦听器 ,并且当收到一个回调消息,表明已选择了一个新的菜单项时…您可以继续更改片段(您将始终启动时发生一个事件,或者您可以在onCreate期间强制执行它)。

您将在字面上将switch / if语句添加到onNavigationItemSelected(MenuItem item)方法。

并调用addFragment(TAG); case而定。

伪代码让您了解:

private void addFragment(final String tag) {
        final Fragment existing = getSupportFragmentManager().findFragmentByTag(tag);

        if (existing == null) {
            final Fragment newInstance = getNewFragmentInstanceWithTag(tag);
            getSupportFragmentManager()
                    .beginTransaction()
                    .replace(getFragmentContainerLayout(), newInstance, tag)
                    .commit();
        }
}

您还需要提供:

private int getFragmentContainerLayout() {
    return R.id.your_fragment_container;
}

和…

public static final String TAB1_TAG = "TAB1_TAG";
public static final String TAB2_TAG = "TAB2_TAG";
public static final String TAB3_TAG = "TAB3_TAG";

protected Fragment getNewFragmentInstanceWithTag(String tag) {
    switch (tag) {
        case TAB1_TAG:
            return Tab1Fragment.newInstance();
        case TAB2_TAG:
            return Tab2Fragment.newInstance();
        case TAB3_TAG:
            return Tab3Fragment.newInstance();
        default:
            return null;
    }
}

那么,FragmentManager / Transaction是什么青蛙呢?

可以将Manager视为一个单例对象(每个应用程序一个),该对象保留对您的Fragments的引用,并可以为您检索Fragments(如果以前存在)。 它处理事务(添加/删除/隐藏/显示等),因此您以后可以回滚它们(例如,在事务中添加片段,如果还添加了addToBackStack()则可以简单地告诉Manager:弹出最后一个事务,有效地回滚。

这是一个怪物。 它有超过9000年的错误,而且不是很直观。 但是一旦习惯了,就可以“使用”。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM