【问题标题】:View binding of a frgament inside a constraint layout not working在约束布局中查看片段的绑定不起作用
【发布时间】:2021-12-07 05:59:39
【问题描述】:

我有以下代码:

activity_reminders.xml

<androidx.constraintlayout.widget.ConstraintLayout 
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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".locationreminders.RemindersActivity">

    <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" />
</androidx.constraintlayout.widget.ConstraintLayout>

ReminderActivity.kt

class RemindersActivity : AppCompatActivity() {

private lateinit var binding: ActivityRemindersBinding

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = ActivityRemindersBinding.inflate(layoutInflater)
    setContentView(binding.root)
}

override fun onOptionsItemSelected(item: MenuItem): Boolean {
    when (item.itemId) {
        android.R.id.home -> {
            (binding.navHostFragment as NavHostFragment).navController.popBackStack()
            return true
        }
    }
    return super.onOptionsItemSelected(item)
}

}

binding.navHostFragment 未解决,我不明白为什么,如果我以任何不同的方式更改视图类型,则“片段”视图绑定有效。 是否可以将视图 vbinding 用于另一个视图中的片段?

【问题讨论】:

  • 您是否在 Gradle 中启用了视图绑定?
  • logcat显示什么错误?
  • 是的,我已启用 buildFeatures { viewBinding true } 并且构建错误是:“未解析的参考:navHostFragment”

标签: android kotlin android-viewbinding


【解决方案1】:

我发现以下作为获取片段的解决方法。

val navHostFragment = findNavController(R.id.nav_host_fragment)
navHostFragment.popBackStack()

我认为不可能将视图绑定与 一起使用,因为片段不是 View 的后代。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多