我有一个带有 4 个按钮的底部导航栏。其中之一是后退按钮,它只是导航回先前显示的片段(我使用一个活动多片段的方法)。基本上一切正常。现在我想知道是否可以不导航回某个片段 A?所以基本上每当这个 Fragment A 是显示的最后一个 Fragment 并且用户点击后退按钮时,它不应该向后导航,而是停留在当前 Fragment 上(并且可能显示一个小的 toast 消息)。
所以在这里你可以看到我实现导航的主要活动:
package com.example.td.bapp;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.FragmentManager;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.NavigationUI;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import com.example.td.bapp.databinding.ActivityMainBinding;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
public class MainActivity extends AppCompatActivity {
public static DataBaseHelper myDB;
public static boolean veryFirstCreation = true;
private ActivityMainBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
View view = binding.getRoot();
setContentView(view);
final NavController navController = Navigation.findNavController(this,
R.id.navHostfragment);
NavigationUI.setupWithNavController(binding.bottomNavigation, navController);
myDB=new DataBaseHelper(this);
if(veryFirstCreation) {
navController.navigate(R.id.FR_LanguageSelection);
veryFirstCreation = false;
}
// Define the bahaviour when clicking on items of the bottomNavigationBar; Overwrites the JetpackNavigation behaviour (automatic navigation using the id specified in the BottomNavigation XML menu file)
binding.bottomNavigation.setOnNavigationItemSelectedListener(
new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
if (item.getItemId()== R.id.BottomNavigation_Back) {
//Here I navigate back to the previous fragment
navController.navigateUp();
}
if (item.getItemId()== R.id.BottomNavigation_Language) {
navController.navigate(R.id.FR_LanguageSelection);
}
if (item.getItemId()== R.id.BottomNavigation_MyItems) {
navController.navigate(R.id.FR_MyItems);
}
if (item.getItemId()== R.id.BottomNavigation_Menu) {
navController.navigate(R.id.FR_Menu);
}
return true;
}
});
};
}
感谢您的每一条评论,也非常感谢您的帮助。
答案 0 :(得分:0)
您可以使用 SupportFragmentManager,这样您就可以知道您的后台堆栈是否包含至少一个片段。在你的 back 函数中使用它(或者在你的 onBackPressed 中,如果需要的话)
FragmentManager fm = getSupportFragmentManager();
if (fm.getBackStackEntryCount() ==1) {
Log.d("ppl","This is the last fragment. Show your message, poppup or whatever you want here")
} else if (fm.getBackStackEntryCount() >1) {
Log.d("ppl","the backstack still have more to show")
fm.popBackStackImmediate();
}