假设我们有一个这样的项目:
class MainActivity : AppCompatActivity() {
private lateinit var drawerLayout: DrawerLayout
private lateinit var appBarConfiguration : AppBarConfiguration
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = DataBindingUtil.setContentView<ActivityMainBinding>(this, R.layout.activity_main)
drawerLayout = binding.drawerLayout
val navController = this.findNavController(R.id.myNavHostFragment)
NavigationUI.setupActionBarWithNavController(this, navController, drawerLayout)
appBarConfiguration = AppBarConfiguration(navController.graph, drawerLayout)
// prevent nav gesture if not on start destination
navController.addOnDestinationChangedListener { nc: NavController, nd: NavDestination, bundle: Bundle? ->
if (nd.id == nc.graph.startDestination) {
drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED)
} else {
drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED)
}
}
NavigationUI.setupWithNavController(binding.navView, navController)
}
链接到一个简单的项目:https://github.com/udacity/andfun-kotlin-android-trivia/blob/blob/step.11-solution-adding-animation-app/app/src/src/main/java/java/java/com/com/com/com/example/android/navigation/mainactivity.kt
我的文件 navgraph 包含片段,也包含一个活动,如果用户从导航抽屉中选择其标题,我想去其中。我想向此活动发送一些数据。如何使用Safe-Args进行操作?
我正在使用:
apply plugin: "androidx.navigation.safeargs"
和
implementation 'androidx.navigation:navigation-fragment:2.0.0'
implementation 'androidx.navigation:navigation-ui:2.0.0'
首先,您必须转到导航图并为活动目标指定参数。这可以通过设计UI或这样的XML完成;
<navigation>
<activity android:id="@+id/someActivity">
<argument
android:name="isEditMode"
app:argType="boolean"
android:defaultValue="false" />
</activity>
</navigation>
此片段假设您将布尔值传递给活动。
此时,您可以构建项目,以便生成所有必需的文件。
然后,在负责启动活动的任何导航菜单项的关注中,您将传递数据;
override boolean onNavigationItemSelected(menuItem: menuItem) {
val id = menuItem.itemId
when (id) {
R.id.openActivity -> {
val bundle = bundleOf("isEditMode" to false)
findNavController().navigate(R.id.someActivity, bundle)
}
}
return true
}
然后在您的活动中,将通行证数据安全获取为;
val safeArguments: MyActivityArgs by navArgs()
val isEditMode = safeArgs.isEditMode)
在您的主activity中使用以下方式:
val navController = this.findNavController(R.id.myNavHostFragment)
navController.addOnDestinationChangedListener { controller, destination, arguments ->
when(destination.id) {
R.id.caixaFragment -> {
var myVar = someMethodThatBringsMyVarValue()
val argument = NavArgument.Builder().setDefaultValue(mayVar).build()
destination.addArgument("idMes", argument)
}
}
}
我在这个问题中从Ayxan Haqverdili那里得到了