Hel*_*oCW 5 android android-jetpack
通常,我val navController: NavController = findNavController(R.id.nav_host_fragment)在代码 A 中使用来查找 NavController,它基于R.id.nav_host_fragment.
现在我在应用程序中使用视图绑定,就像代码B一样,如果我使用视图绑定,我该如何使用NavController?
顺便说一句,在我看来, R.id.nav_host_fragment视图绑定将不可用,对吧?
代码A
class TasksActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.tasks_act)
val navController: NavController = findNavController(R.id.nav_host_fragment)
}
}
Run Code Online (Sandbox Code Playgroud)
代码B
class TasksActivity : AppCompatActivity() {
private lateinit var binding: TasksActBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = TasksActBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
//val navController: NavController = findNavController(R.id.nav_host_fragment)
}
}
Run Code Online (Sandbox Code Playgroud)
任务_act.xml
<androidx.drawerlayout.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".tasks.TasksActivity"
tools:openDrawer="start">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?attr/actionBarSize"
android:theme="@style/Toolbar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
</com.google.android.material.appbar.AppBarLayout>
<fragment
android:id="@+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:navGraph="@navigation/nav_graph" />
</LinearLayout>
..
</androidx.drawerlayout.widget.DrawerLayout>
Run Code Online (Sandbox Code Playgroud)
我们使用 ViewBinding 来获取视图本身的引用。如果您在 TextView 中使用视图绑定,您将获得视图的引用。
在 NavCotroller 的情况下,如果使用 ViewBinding,您将获得对 Fragment 的引用,而findNavController期望 ViewId 为整数类型。
findNavController(@IdRes viewId: int)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6107 次 |
| 最近记录: |