在底部导航栏中保存片段状态

时间:2021-05-14 20:55:43

标签: java android kotlin android-fragments android-activity

我有一个活动,它基本上是一个包含片段的导航底部栏。如果用户已登录,底部导航将显示 4 个片段:市场、收藏、上传和个人资料。如果用户是访客,则有两个片段:市场和登录。

以前,每次有人从一个片段交换到另一个片段时,它都会再次生成。但是,我想保留片段的状态,所以如果有人在市场上应用了过滤器并回来了,它必须保持过滤器的应用。我尝试实施此解决方案 https://medium.com/@oluwabukunmi.aluko/bottom-navigation-view-with-fragments-a074bfd08711,但我觉得目前还不是最好的。

导航活动的代码是:

public class NavigationActivity extends AppCompatActivity {

    final Fragment market= new MarketFragment();
    final Fragment favorite = new FavoriteFragment();
    final Fragment updateProduct = new AddProductFragment();
    final Fragment userProfile = new UserProfileFragment();
    final Fragment loginregister = new LoginOrRegisterFragment();
    final FragmentManager fm = getSupportFragmentManager();
    Fragment active = market;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(UnipopApp.usuariLoggejat.getUserLogged() != null){
            setContentView(R.layout.main);
        }
        else{
            setContentView(R.layout.main_guest);
        }
        setUpNavigation();
    }

    public void setUpNavigation() {
        BottomNavigationView bottomNavigationView;
        if(UnipopApp.usuariLoggejat.getUserLogged() != null) {
            bottomNavigationView = findViewById(R.id.bottom_navigation);
            bottomNavigationView.setOnNavigationItemSelectedListener(mOnNavegationItemSelectedListener);
            fm.beginTransaction().add(R.id.nav_host_fragment, favorite, "2").hide(favorite).commit();
            fm.beginTransaction().add(R.id.nav_host_fragment, updateProduct, "3").hide(updateProduct).commit();
            fm.beginTransaction().add(R.id.nav_host_fragment, userProfile, "5").hide(userProfile).commit();
            fm.beginTransaction().add(R.id.nav_host_fragment, market, "1").commit();
        }
        else {
            bottomNavigationView = findViewById(R.id.bottom_navigation_guest);
            bottomNavigationView.setOnNavigationItemSelectedListener(mOnNavegationItemSelectedListener);
            fm.beginTransaction().add(R.id.nav_host_fragment_guest, loginregister, "6").hide(loginregister).commit();
            fm.beginTransaction().add(R.id.nav_host_fragment_guest, market, "1").commit();
        }
    }

    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavegationItemSelectedListener
        = new BottomNavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            switch (item.getItemId()){
                case R.id.action_home:
                    fm.beginTransaction().hide(active).show(market).commit();
                    active = market;
                    return true;
                case R.id.action_favorites:
                    fm.beginTransaction().hide(active).show(favorite).commit();
                    active = favorite;
                    return true;
                case R.id.addProduct_fragment:
                    fm.beginTransaction().hide(active).show(updateProduct).commit();
                    active = updateProduct;
                    return true;
                case R.id.action_user_profile:
                    fm.beginTransaction().hide(active).show(userProfile).commit();
                    active = userProfile;
                    return true;
                case R.id.action_user_profile_guest:
                    fm.beginTransaction().hide(active).show(loginregister).commit();
                    active = loginregister;
                    return true;
            }
            return false;
        }
    };
}

它有效,但我不得不删除导航图...然而,问题是当有人将产品标记为市场上最喜欢的产品并移动到最喜欢的片段时,它并没有出现。显然,它只是再次显示片段,它不会通过来自服务器的调用重新生成它。

我正在寻找其他选择,因为我不喜欢这个解决方案。如果有人能帮我一把,那就太好了。

谢谢

2 个答案:

答案 0 :(得分:0)

使用底部导航视图和片段导航的推荐解决方案。使用 Activity's SharedViewModel 保持所有导航片段的状态。

布局 XML (rees/layout/activity_main.xml)

        var leftdata = {
          labels: [0, 1, 2, 3, 4, 5], 
          datasets: [{
              label: "A",
              backgroundColor: 'rgba(0, 0, 255, 0.5)',
              data: [12, 19, 3, 5, 1],
              xAxisID: "A"
            },
            {
              label: "B",
              backgroundColor: 'rgba(0, 255, 0, 0.5)',
              data: [14, 19, 6, 2, 4],
              xAxisID: "B"
            }
          ]
        };
        
        var rightdata = {
          labels: [0, 1, 2, 3, "4", 5], // the #4 being a string is the only difference
          datasets: [{
              label: "A",
              backgroundColor: 'rgba(0, 0, 255, 0.5)',
              data: [12, 19, 3, 5, 1],
              xAxisID: "A"
            },
            {
              label: "B",
              backgroundColor: 'rgba(0, 255, 0, 0.5)',
              data: [14, 19, 6, 2, 4],
              xAxisID: "B"
            }
          ]
        };

        var options = {
          scales: {
            xAxes: [{
                id: "A",
                display: false,
                barPercentage: 1.25,
                ticks: {
                  max: 4 
                }
              },
              {
                id: "B",
                display: false,
                stacked: true,
                offset: true,
                barPercentage: 1.25,
                ticks: {
                  max: 4
                }
              },
              {
                display: true,
                ticks: {
                  autoSkip: false,
                  max: 5 
                }
              }
            ],

            yAxes: [{
              id: "bar-y-axis1",
              ticks: {
                beginAtZero: true
              }
            }]

          }
        };

        var leftctx = document.getElementById("topcanvas").getContext("2d");
        new Chart(leftctx, {
          type: 'bar',
          data: leftdata,
          options: options
        });
        var rightctx = document.getElementById("bottomcanvas").getContext("2d");
        new Chart(rightctx, {
          type: 'bar',
          data: rightdata,
          options: options
        });

导航 XML (res/navigation/core_navigation.xml)

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<com.google.android.material.bottomnavigation.BottomNavigationView
    android:id="@+id/bottom_navigation"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:layout_constraintBottom_toBottomOf="parent"
    app:labelVisibilityMode="labeled"
    app:menu="@menu/bottom_navigation_menu" />

<androidx.fragment.app.FragmentContainerView
    android:id="@+id/nav_host_fragment"
    android:name="androidx.navigation.fragment.NavHostFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:defaultNavHost="true"
    app:layout_constraintBottom_toTopOf="@id/bottom_navigation"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:navGraph="@navigation/core_navigation" />

</androidx.constraintlayout.widget.ConstraintLayout>

菜单 XML (res/menu/bottom_navigation_menu.xml)

<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
app:startDestination="@+id/navigation_feed">

<fragment
    android:id="@+id/navigation_home"
    android:name="com.example.HomeFragment"
    android:label="@string/home_title"
    tools:layout="@layout/home_fragment" />

<fragment
    android:id="@+id/navigation_favorites"
    android:name="com.example.FavoritesFragment"
    android:label="@string/favorites_title"
    tools:layout="@layout/favorites_fragment" />

<!--Fill this with other fragments like above-->

</navigation>

活动

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
    android:id="@+id/navigation_home"
    android:enabled="true"
    android:icon="@drawable/ic_home"
    android:title="@string/home_title"/>
<item
    android:id="@+id/navigation_favorites"
    android:enabled="true"
    android:icon="@drawable/ic_favorites"
    android:title="@string/favorites_title"/>

<!--Fill this with other fragments like above-->

</menu>

答案 1 :(得分:0)

您可以在片段的视图模型中保存过滤器选择。