3

我在我的项目中使用 viewBinding,效果很好。但是我有一个问题getRoot()在这一行中无法解决View view = binding.getRoot()。我的代码运行良好,没有任何崩溃,但我希望错误消失,似乎无法解决问题。我已经尝试禁用和重新启用 viewBinding、使缓存无效以及重新启动和清理项目,但这个恼人的错误似乎并没有消失。

这是我的代码

构建.gradle

...
viewBinding {
        enabled = true
    }
...

主要活动

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityMainBinding binding = ActivityMainBinding.inflate(getLayoutInflater());
        View view = binding.getRoot();
        setContentView(view);

        binding.bottomNavigationView.setOnNavigationItemSelectedListener(navListener);
        ...
}

活动主要

...
<com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottom_navigation_view"
        style="@style/Widget.MaterialComponents.BottomNavigationView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:background="?attr/colorSurface"
        app:menu="@menu/bottom_nav_menu" />
...
4

2 回答 2

3

我终于修好了!!

我阅读了在相应布局中获取根视图(最外层视图)的文档binding.getRoot()所以我想我会给根视图一个id,然后调用那个id。

活动主

<RelativeLayout
        android:id="@+id/root"
        ...>
</RelativeLayout>

主要活动

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityMainBinding binding = ActivityMainBinding.inflate(getLayoutInflater());
        View view = binding.root;
        setContentView(view);
        ...
}
于 2020-04-03T12:39:34.357 回答
1

I had the same problem and I know that your solution works, but it is kind of a work-around.

My problem came from the fact that my root view was <layout> which is not qualified to be a root view.

于 2021-02-20T17:26:08.170 回答