如何从导航抽屉选项卡导航回 activity?

How to navigate back to activity from navigation drawer tabs?

我有一个带 3 个主要选项卡的导航抽屉 https://i.stack.imgur.com/SIjdx.jpg。在每个选项卡中,即设置和其余选项卡中,我实现了一个顶部后退按钮,returns 到 单击主页 activity。我也尝试处理底部后退按钮,但现在的问题是,如果我单击底部后退按钮(phone 手势导航)https://i.stack.imgur.com/RYW16.jpg,它只会退出应用程序而不是 return如期回家Activity。

我想让它 return 回到主页 activity 这样我就可以使用顶部和底部的后退按钮浏览选项卡,我该怎么做请更正此问题?

我在本站查过类似问题,还没有找到解决办法。

这是我的设置代码(我对其他选项卡也使用相同的代码):

public class Settings extends Fragment {

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.settings, container, false);

        requireActivity().getOnBackPressedDispatcher().addCallback(getViewLifecycleOwner(), new OnBackPressedCallback(true) {
            @Override
            public void handleOnBackPressed() {
                requireActivity().finish();
            }
        });

        return view;

    }
}

编辑:

首页Activity:

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.dubai, R.drawable.norway, R.drawable.eiffel_tower, R.drawable.hong_kong, R.drawable.statue_of_liberty,
            R.drawable.beijing, R.drawable.chicago, R.drawable.colombia, R.drawable.vienna, R.drawable.tokyo};
    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.ic_baseline_arrow_back_24);

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

            // Fragments that you want to show the back button
            if (destination.getId() == R.id.settings_id || destination.getId() == R.id.ads_upgrade_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.dubai);
        _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
    }
}

使用 onBackPressed() 函数覆盖后退按钮的操作。这是一些示例代码:

override fun onBackPressed() {
    val intent = Intent(requireActivity(),HomeActivity::class.java)
    requireActivity().startActivity(intent)
}

onBackPressed() 函数中写入您想要的操作。

为了 return 到 activity 而不是在单击底部后退按钮时存在该应用程序:

从所有相关片段(如 SettingFragment)中删除以下回调:

requireActivity().getOnBackPressedDispatcher().addCallback(getViewLifecycleOwner(), new OnBackPressedCallback(true) {
    @Override
    public void handleOnBackPressed() {
        requireActivity().finish();
    }
});

导航组件会处理返回堆栈,所以不用担心。当你回到家时会出现一个小问题activity;你会看到向上按钮而不是汉堡图标;要解决此问题,您需要在返回 addOnDestinationChangedListener

时添加 toggle.setDrawerIndicatorEnabled(true)

所以,在 HomeActivity:

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.ic_baseline_arrow_back_24);
        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.settings_id || destination.getId() == R.id.ads_upgrade_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);
    }

});

声音应该会继续播放,因为您没有创建全新的 activity。