带有片段的底部导航视图(不重新创建片段)

时间:2019-07-20 11:02:49

标签: android android-navigationview

我使用android.support.design.widget.BottomNavigationView。我有替换framents的问题。我不想每次选择iteam时都重新创建frament,所以我写:

    //MainACtivity

     final Fragment fragment1 = new HomeFragment();
        final Fragment fragment2 = new DashboardFragment();
        final Fragment fragment3 = new NotificationsFragment();
        final FragmentManager fm = getSupportFragmentManager();
        Fragment active = fragment1;

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

            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);


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

            fm.beginTransaction().add(R.id.main_container, fragment3, "3").hide(fragment3).commit();
            fm.beginTransaction().add(R.id.main_container, fragment2, "2").hide(fragment2).commit();
                fm.beginTransaction().add(R.id.main_container,fragment1, "1").commit();
    }

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

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            switch (item.getItemId()) {
                case R.id.navigation_home:
                    fm.beginTransaction().hide(active).show(fragment1).commit();
                    active = fragment1;
                    return true;

                case R.id.navigation_dashboard:
                    fm.beginTransaction().hide(active).show(fragment2).commit();
                    active = fragment2;
                    return true;

                case R.id.navigation_notifications:
                    fm.beginTransaction().hide(active).show(fragment3).commit();
                    active = fragment3;
                    return true;
            }
            return false;
        }
    };

主要问题是片段之一的显示方式类似于背景img(如图片enter image description here所示)。有时会发生。我不知道原因;

0 个答案:

没有答案