使用底部导航栏防止片段刷新

时间:2019-06-12 16:23:58

标签: android android-fragments

我有以下底部导航条代码可在3个片段之间切换:

public class MainActivity extends AppCompatActivity {

    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            Fragment fragment = null;

            switch (item.getItemId()) {
                case R.id.navigation_home:
                    fragment = new HomeFragment();
                    break;

                case R.id.navigation_dashboard:
                    fragment = new DashboardFragment();
                    break;

                case R.id.navigation_notifications:
                    fragment = new NotificationsFragment();
                    break;

            }

            return loadFragment(fragment);
        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        loadFragment(new HomeFragment());


        BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
    }

    private boolean loadFragment(Fragment fragment) {
        //switching fragment
        if (fragment != null) {
            getSupportFragmentManager()
                    .beginTransaction()
                    .replace(R.id.fragment_container, fragment)
                    .commit();
            return true;
        }
        return false;
    }
}

片段中有带有列表的RecyclerViews。每次我在选项卡之间(片段之间)切换时,看起来片段已重新加载,并且列表跳到顶部。我想避免重新加载,以使用户在切换片段之前停留在查看过的列表中的同一位置

2 个答案:

答案 0 :(得分:1)

问题在于您每次都在创建一个新实例。您可以像这样缓存实例:

    private Fragment mHomeFragment = new HomeFragment();
    private Fragment mDashboardFragment = new DashboardFragment();
    private Fragment mNotificationsFragment = new NotificationsFragment();


    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        Fragment fragment = null;

        switch (item.getItemId()) {
            case R.id.navigation_home:
                fragment = mHomeFragment;
                break;

            case R.id.navigation_dashboard:
                fragment = mDashboardFragment;
                break;

            case R.id.navigation_notifications:
                fragment = mNotificationsFragment;
                break;

        }

        return loadFragment(fragment);
    }

答案 1 :(得分:0)

如我们所见,单击底部导航时始终会替换片段,而replace表示删除了先前的片段并进行了状态清理。解决方法是不要每次都创建片段,而是使用attach / detach方法显示实际片段。 Here is already described关于这些方法。