0

我可以用繁琐的方法解决它,所以如果您不发布解决方法而是记录解决方案,我将不胜感激。

我正在尝试将以下代码片段添加到onCreateView()片段中,但是“感谢”安全调用(或我的代码设计)事情变得复杂了。在Kotlin 部分之后显示警告以在(相当于Java 中)之后TabLayoutMediator(activity添加安全调用 ( ) ,这可能是.?.activitygetActivitynull

尝试任何解决方案之前的原始代码片段

TabLayoutMediator(activity.findViewById(R.id.tabs), view.findViewById(R.id.view_pager),
                TabLayoutMediator.OnConfigureTabCallback { tab, position ->
                    // Styling each tab here
                    tab.text = mValueHeadlineCategoryList[position]
                }).attach()

1)试图通过添加来解决safe call(失败)

现在添加安全调用违背了TabLayoutMediator输入参数,我收到type mismatch Required:TabLayout Found:TabLayout?警告TabLayoutMediator

TabLayoutMediator(activity?.findViewById(R.id.tabs), view.findViewById(R.id.view_pager),
            TabLayoutMediator.OnConfigureTabCallback { tab, position ->
                tab.text = mValueHeadlineCategoryList[position]
            }).attach()

2)尝试通过之前的空检查来解决safe call(失败)

添加空检查,但现在 Kotlin 给出了TabLayoutMediator(activity部分警告Smart cast to 'FragmentActivity' is impossible, because 'activity' is a property that has open or custom gette

if (activity != null) {
            TabLayoutMediator(activity.findViewById(R.id.tabs), view.findViewById(R.id.view_pager),
                TabLayoutMediator.OnConfigureTabCallback { tab, position ->
                    tab.text = mValueHeadlineCategoryList[position]
                }).attach()
        }
4

2 回答 2

3

替换activity requireActivity()

于 2019-08-10T13:19:24.783 回答
3

简单的修复:你可以这样做

   activity?.let { instance ->
            TabLayoutMediator(instance.findViewById(R.id.tabs), view.findViewById(R.id.view_pager),
                TabLayoutMediator.OnConfigureTabCallback { tab, position ->
                    tab.text = mValueHeadlineCategoryList[position]
                }).attach()
}
于 2019-08-10T13:19:42.380 回答