以下是使用Android导航组件在图形之间导航的解决方法的示例代码:
dependencies {
def nav_version = "2.3.5"
implementation "androidx.navigation:navigation-fragment-ktx:$nav_version"
implementation "androidx.navigation:navigation-ui-ktx:$nav_version"
}
class MainActivity : AppCompatActivity() {
private lateinit var navController: NavController
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
navController = navHostFragment.navController
}
override fun onSupportNavigateUp(): Boolean {
return navController.navigateUp() || super.onSupportNavigateUp()
}
}
class FirstFragment : Fragment() {
private lateinit var binding: FragmentFirstBinding
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentFirstBinding.inflate(inflater, container, false)
val navigateToSecondButton = binding.buttonNavigateToSecond
navigateToSecondButton.setOnClickListener(
Navigation.createNavigateOnClickListener(R.id.action_firstFragment_to_secondFragment)
)
return binding.root
}
}
通过这些步骤,您可以使用Android导航组件在图形之间进行导航。在这个示例中,点击FirstFragment中的按钮将导航到SecondFragment。