删除带有片段的底部导航视图

问题描述 投票:0回答:4

我有 2 个活动,其中有一个单独的

NavHostFragment
,其中托管 3 个片段,然后这 3 个片段显示在我的活动布局中
ContainerView
。 注意:我的 2 个活动具有相同的名称并使用相同的布局,唯一的区别是它们位于不同的目录中并处理略有不同的任务。

最初,我计划使用应用程序的所有片段,但现在,我决定在第一个版本中仅使用一个片段,然后稍后再处理其他片段,因为它的任务是一次处理所有片段

所以我想安全地删除底部导航视图和其他两个片段(第二个和第三个片段)。

我最初已经尝试通过删除这些片段并删除与其相关的任何代码来自己完成此操作,但它出现了很多错误,所以我决定将其带到这里,看看是否有人可以提供最安全的帮助这样我就可以删除它们,以便我的第一个片段 可以继续运行,没有任何问题。

它是一个天气应用程序,因此我在第一个片段上收到当前城市的更新。我应该每小时和每天收到第二个和第三个片段的更新,但我已经停止了我的计划,现在,我只想使用第一个片段。

主要代码如下:

活动\主页活动:

public class HomeActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
    private DrawerLayout drawer;
    // Last update time, click sound, search button, search panel.
    TextView timeField;
    MediaPlayer player;
    ImageView Search;
    EditText textfield;
    // For scheduling background image change(using constraint layout, start counting from dubai, down to statue of liberty.
    ConstraintLayout constraintLayout;
    public static int count = 0;
    int[] drawable = new int[]{R.drawable.nyc, R.drawable.lofoten_islands, R.drawable.parque, R.drawable.moraine_lake, R.drawable.eiffel_tower,
            R.drawable.whitehaven_beach, R.drawable.london, R.drawable.cape_town, R.drawable.burj_al_arab,R.drawable.atuh_beach};
    Timer _t;

    private WeatherDataViewModel viewModel;
    private AppBarConfiguration appBarConfiguration;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        // use home activity layout.

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        // Allow activity to make use of the toolbar

        drawer = findViewById(R.id.drawer_layout);
        NavigationView navigationView = findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        // Hiding default Drawer fragment that has the BottomNavView
        navigationView.getMenu().findItem(R.id.main_id).setVisible(false);

        viewModel = new ViewModelProvider(this).get(WeatherDataViewModel.class);

        // Trigger action to open & close navigation drawer
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar
                , R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        timeField = findViewById(R.id.textView9);
        Search = findViewById(R.id.imageView4);
        textfield = findViewById(R.id.textfield);
        //  find the id's of specific variables.


        BottomNavigationView bottomNavigationView = findViewById(R.id.bottomNavigationView);
        // host 3 fragments along with bottom navigation.
        final NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.fragment);
        assert navHostFragment != null;
        final NavController navController = navHostFragment.getNavController();

        // Make hourly & daily tab unusable
        bottomNavigationView.setOnNavigationItemSelectedListener(item -> {

            if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
                getSupportFragmentManager().popBackStack();
            }
            return false;
        });

        toggle.setToolbarNavigationClickListener(v -> {
            // Enable the functionality of opening the side drawer, when the burger icon is clicked
            toggle.setDrawerIndicatorEnabled(true);
            navController.navigate(R.id.main_id);
        });

        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        // remove up button from all these fragments
        appBarConfiguration = new AppBarConfiguration.Builder(
                R.id.main_id) // remove up button from all these fragments >> Keep up button in R.id.nav_setting, R.id.nav_slideshow
                .setOpenableLayout(drawer)
                .build();

        NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
        NavigationUI.setupWithNavController(navigationView, navController);

        // navController.addOnDestinationChangedListener((controller, destination, arguments) -> navController.popBackStack(destination.getId(), false));
        // navController.addOnDestinationChangedListener((controller, destination, arguments) -> {
        // });

        navController.addOnDestinationChangedListener((controller, destination, arguments) -> {

            // Hide/show top search bar
            if (destination.getId() == R.id.main_id) {
                Search.setVisibility(View.VISIBLE);
                textfield.setVisibility(View.VISIBLE);

            } else {
                Search.setVisibility(View.GONE);
                textfield.setVisibility(View.GONE);
            }

            // Fragments that you want to show the back button
            if (destination.getId() == R.id.about_id || destination.getId() == R.id.privacy_policy_id) {
                // Disable the functionality of opening the side drawer, when the burger icon is clicked
                toggle.setDrawerIndicatorEnabled(false);
            }

        });

        // For scheduling background image change
        constraintLayout = findViewById(R.id.layout);
        constraintLayout.setBackgroundResource(R.drawable.nyc);
        _t = new Timer();
        _t.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                // run on ui thread
                runOnUiThread(() -> {
                    if (count < drawable.length) {

                        constraintLayout.setBackgroundResource(drawable[count]);
                        count = (count + 1) % drawable.length;
                    }
                });
            }
        }, 5000, 5000);

        Search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                // make click sound when search button is clicked.
                player = MediaPlayer.create(HomeActivity.this, R.raw.click);
                player.start();

                getWeatherData(textfield.getText().toString().trim());
                // make use of some fragment's data

                Fragment currentFragment = navHostFragment.getChildFragmentManager().getFragments().get(0);
                if (currentFragment instanceof FirstFragment) {
                    FirstFragment firstFragment = (FirstFragment) currentFragment;
                    firstFragment.getWeatherData(textfield.getText().toString().trim());
                } else if (currentFragment instanceof SecondFragment) {
                    SecondFragment secondFragment = (SecondFragment) currentFragment;
                    secondFragment.getWeatherData(textfield.getText().toString().trim());
                } else if (currentFragment instanceof ThirdFragment) {
                    ThirdFragment thirdFragment = (ThirdFragment) currentFragment;
                    thirdFragment.getWeatherData(textfield.getText().toString().trim());
                }
            }

            private void getWeatherData(String name) {

                ApiInterface apiInterface = ApiClient.getClient().create(ApiInterface.class);

                Call<Example> call = apiInterface.getWeatherData(name);

                call.enqueue(new Callback<Example>() {
                    @Override
                    public void onResponse(@NonNull Call<Example> call, @NonNull Response<Example> response) {

                        try {
                            assert response.body() != null;
                            timeField.setVisibility(View.VISIBLE);
                            timeField.setText("First Updated:" + " " + response.body().getDt());
                        } catch (Exception e) {
                            timeField.setVisibility(View.GONE);
                            timeField.setText("First Updated: Unknown");
                            Log.e("TAG", "No City found");
                            Toast.makeText(HomeActivity.this, "No City found", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(@NotNull Call<Example> call, @NotNull Throwable t) {
                        t.printStackTrace();
                    }

                });
            }

        });
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.about_id:
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment,
                        new About()).commit();
                break;
            case R.id.privacy_policy_id:
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment,
                        new Privacy_Policy()).commit();
                break;
        }
        drawer.closeDrawer(GravityCompat.START);

        return true;
    }

    @Override
    public void onBackPressed() {
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
            // Open/close drawer animation
        }
    }

    @Override
    protected void onPause () {
        super.onPause();
        if (viewModel.getMediaPlayer() != null)
            viewModel.getMediaPlayer().pause();
    }

    @Override
    protected void onResume () {
        super.onResume();
        if (viewModel.getMediaPlayer() != null) {
            viewModel.getMediaPlayer().start();
            viewModel.getMediaPlayer().setLooping(true);
        }
    }

    @Override
    public boolean onSupportNavigateUp() {
        final NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.fragment);
        assert navHostFragment != null;
        final NavController navController = navHostFragment.getNavController();

        return NavigationUI.navigateUp(navController, appBarConfiguration)
                || super.onSupportNavigateUp(); // navigateUp  tries to pop the backstack
    }
}

Lightweatherforecast\HomeActivity:

public class HomeActivity extends AppCompatActivity {
    private DrawerLayout drawer;
    // Last update time, click sound, search button, search panel.
    TextView timeField;
    MediaPlayer player;
    ImageView Search;
    ConstraintLayout searchbar;
    EditText textfield;
    // For scheduling background image change(using constraint layout, start counting from dubai, down to statue of liberty.
    ConstraintLayout constraintLayout;
    public static int count = 0;
    int[] drawable = new int[]{R.drawable.nyc, R.drawable.lofoten_islands, R.drawable.parque, R.drawable.moraine_lake, R.drawable.eiffel_tower,
            R.drawable.whitehaven_beach, R.drawable.london, R.drawable.cape_town, R.drawable.burj_al_arab, R.drawable.atuh_beach};
    Timer _t;

    private WeatherDataViewModel viewModel;
    private AppBarConfiguration appBarConfiguration;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        // use home activity layout.

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        // Allow activity to make use of the toolbar

        drawer = findViewById(R.id.drawer_layout);
        NavigationView navigationView = findViewById(R.id.nav_view);

        // host 3 fragments along with bottom navigation.
        final NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.fragment);
        assert navHostFragment != null;
        final NavController navController = navHostFragment.getNavController();

        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        // remove up button from all these fragments
        appBarConfiguration = new AppBarConfiguration.Builder(
                R.id.main_id) // remove up button from all these fragments >> Keep up button in R.id.nav_setting, R.id.nav_slideshow
                .setOpenableLayout(drawer)
                .build();

        // Hiding default Drawer fragment that has the BottomNavView
        navigationView.getMenu().findItem(R.id.main_id).setVisible(false);

        viewModel = new ViewModelProvider(this).get(WeatherDataViewModel.class);

        // Trigger action to open & close navigation drawer
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar
                , R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        timeField = findViewById(R.id.textView9);
        Search = findViewById(R.id.imageView4);
        textfield = findViewById(R.id.textfield);
        searchbar = findViewById(R.id.searchbar);
        //  find the id's of specific variables.

        NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
        NavigationUI.setupWithNavController(navigationView, navController);

        toggle.setToolbarNavigationClickListener(v -> {
            // Enable the functionality of opening the side drawer, when the burger icon is clicked
            toggle.setDrawerIndicatorEnabled(true);
            navController.navigate(R.id.main_id);
        });

        navController.addOnDestinationChangedListener((controller, destination, arguments) -> {

            // Hide/show top search bar
            if (destination.getId() == R.id.main_id) {
                searchbar.setVisibility(View.VISIBLE);
                toggle.setHomeAsUpIndicator(R.drawable.nav_back_arrow);
                toggle.setDrawerIndicatorEnabled(true); // <<< Add this line of code to enable the burger icon

            } else {
                searchbar.setVisibility(View.GONE);
            }

            // Fragments that you want to show the back button
            if (destination.getId() == R.id.about_id || destination.getId() == R.id.privacy_policy_id) {
                // Disable the functionality of opening the side drawer, when the burger icon is clicked
                toggle.setDrawerIndicatorEnabled(false);
            }

        });

        // For scheduling background image change
        constraintLayout = findViewById(R.id.layout);
        constraintLayout.setBackgroundResource(R.drawable.nyc);
        _t = new Timer();
        _t.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                // run on ui thread
                runOnUiThread(() -> {
                    if (count < drawable.length) {

                        constraintLayout.setBackgroundResource(drawable[count]);
                        count = (count + 1) % drawable.length;
                    }
                });
            }
        }, 5000, 5000);

        Search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                // make click sound when search button is clicked.
                player = MediaPlayer.create(HomeActivity.this, R.raw.click);
                player.start();

                getWeatherData(textfield.getText().toString().trim());
                // make use of some fragment's data

                Fragment currentFragment = navHostFragment.getChildFragmentManager().getFragments().get(0);
                if (currentFragment instanceof MainFragment) {
                    ((MainFragment) currentFragment).getWeatherData(textfield.getText().toString().trim());
                }
            }

            private void getWeatherData(String name) {

                ApiInterface apiInterface = ApiClient.getClient().create(ApiInterface.class);

                Call<Example> call = apiInterface.getWeatherData(name);

                call.enqueue(new Callback<Example>() {
                    @Override
                    public void onResponse(@NonNull Call<Example> call, @NonNull Response<Example> response) {

                        try {
                            assert response.body() != null;
                        } catch (Exception e) {
                            Log.e("TAG", "No City found");
                            Toast.makeText(HomeActivity.this, "No City found", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(@NotNull Call<Example> call, @NotNull Throwable t) {
                        t.printStackTrace();
                    }

                });
            }

        });
    }

    @Override
    public void onBackPressed() {
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
            // Open/close drawer animation
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (viewModel.getMediaPlayer() != null)
            viewModel.getMediaPlayer().pause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (viewModel.getMediaPlayer() != null) {
            viewModel.getMediaPlayer().start();
            viewModel.getMediaPlayer().setLooping(true);
        }
    }

    @Override
    public boolean onSupportNavigateUp() {
        final NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.fragment);
        assert navHostFragment != null;
        final NavController navController = navHostFragment.getNavController();

//        return NavigationUI.navigateUp(navController,drawer);

        return NavigationUI.navigateUp(navController, appBarConfiguration)
                || super.onSupportNavigateUp(); // navigateUp  tries to pop the backstack
    }
}

MainFragment(Navhost 片段):

public class MainFragment extends Fragment {

    private NavHostFragment navHostFragment;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_main, container, false);
//
        BottomNavigationView bottomNavigationView = rootView.findViewById(R.id.bottomNavigationView);

        navHostFragment = (NavHostFragment) getChildFragmentManager().findFragmentById(R.id.nav_host_fragment_content_bottom_nav_view);
        if (navHostFragment != null) {
            NavController navController = navHostFragment.getNavController();
            NavigationUI.setupWithNavController(bottomNavigationView, navController);
        }

        requireActivity().getOnBackPressedDispatcher().addCallback(getViewLifecycleOwner(), new OnBackPressedCallback(true) {
            @Override
            public void handleOnBackPressed() {
                // Exit the app when back is pressed
                requireActivity().finish();
            }
        });

        return rootView;

    }

    public void getWeatherData(String name) {

        Fragment currentFragment = navHostFragment.getChildFragmentManager().getFragments().get(0);
        if (currentFragment instanceof FirstFragment) {
            FirstFragment firstFragment = (FirstFragment) currentFragment;
            firstFragment.getWeatherData(name);
        } else if (currentFragment instanceof SecondFragment) {
            SecondFragment secondFragment = (SecondFragment) currentFragment;
            secondFragment.getWeatherData(name);
        } else if (currentFragment instanceof ThirdFragment) {
            ThirdFragment thirdFragment = (ThirdFragment) currentFragment;
            thirdFragment.getWeatherData(name);
        }
    }
}

其他包括:

*FirstFragment 
*SecondFragment
*ThirdFragment with their respective layouts
*Navigation and menu layouts.

我暂时不会发布它们,如果需要的话,为了降低复杂性,请不要发布 犹豫不决要问。

java android android-fragments bottomnavigationview
4个回答
1
投票

因此,当前的导航总结如下:

HomeActivity 
    MainFragment
        BottomNavigationView navGraph
            FirstFragment
            SecondFragment
            ThirdFragment  
    Other fragments...  

你需要:

  • 安全移除
    BottomNavigationView
  • 仅保留
    FirstFragment
    并去掉
    SecondFragment
    ThirdFragment

由于

MainFragment
仅托管
BottomNavigationView
;然后直接用
FirstFragment
替换即可;所以导航是:

HomeActivity 
    FirstFragment
    Other fragments...  

要做到这一点:

1。在 HomeActivity 的主导航图中:

  • MainFragment
    替换为
    FirstFragment
    (将
    FirstFragment
    部分从
    BottomNavigationView
    navGraph 复制到主 navGraph。
  • FirstFragment
    的 id 重构为与
    MainFragment
    关联的 id,因为该 id 在
    HomeActivity
    中使用(或者您可以通过将其重构为
    FirstFragment
    来实现另一种方式)

2。在

HomeActivity
中,将下面代码片段中的
MainFragment
替换为 FirstFragment:

if (currentFragment instanceof MainFragment) {
    ((MainFragment) currentFragment).getWeatherData(textfield.getText().toString().trim());
}

所以,将会是:

if (currentFragment instanceof FirstFragment) {
    ((FirstFragment) currentFragment).getWeatherData(textfield.getText().toString().trim());
}

这是共享代码中出现的内容;但您可以将每一次出现的

MainFragment
替换为
FirstFragment
,并进行任何需要的重构。

现在,您可以安全地删除

MainFragment
的所有后代、
BottomNavigationView
、第二个和第三个片段;及其资源(布局、菜单...),或者如果您打算将来重用它们,请将它们放在一边。


1
投票

您尝试使用底部导航吗?

android:visibility="gone"

我以前也做过同样的事情。


0
投票
navController.addOnDestinationChangedListener { _, destination, _ ->

 if(destination.id == R.id.first_fragment) {
    // your intro fragment will hide your bottomNavigationView
    bottomNavigationView.visibility = View.GONE
  } else if (destination.id == R.id.second_fragment){
   // your second fragment will show your bottomNavigationView
   bottomNavigationView.visibility = View.VISIBLE
 }
}

您可以根据相关目的地隐藏和显示。


0
投票

您应该在 MainActivity 中编写此代码。

navController.addOnDestinationChangedListener { _, destination, _ ->
        when (destination.id) {
            R.id.navigation_order_active,
            R.id.navigation_order_open,
            R.id.navigation_main_more -> binding.navView.isVisible = true

            else -> binding.navView.isVisible = true
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.