在Android导航组件中,
下面是一个使用NavHostFragment和NavController的示例代码:
implementation 'androidx.navigation:navigation-fragment-ktx:2.3.5'
implementation 'androidx.navigation:navigation-ui-ktx:2.3.5'
import androidx.navigation.NavController;
import androidx.navigation.fragment.NavHostFragment;
public class MainActivity extends AppCompatActivity {
private NavController navController;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 获取NavHostFragment
NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager()
.findFragmentById(R.id.nav_host_fragment);
// 获取NavController
navController = navHostFragment.getNavController();
}
// 处理导航事件
@Override
public boolean onSupportNavigateUp() {
return navController.navigateUp() || super.onSupportNavigateUp();
}
}
import androidx.navigation.Navigation;
public class FirstFragment extends Fragment {
private Button nextButton;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_first, container, false);
nextButton = view.findViewById(R.id.nextButton);
nextButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 导航到SecondFragment
Navigation.findNavController(v).navigate(R.id.action_firstFragment_to_secondFragment);
}
});
return view;
}
}
通过以上代码示例,您可以使用NavHostFragment和NavController来实现导航功能,并处理导航事件,而无需同时使用< navigation >和NavigationItemSelectedListener。