Kotlin SurfaceView / lateinit 属性 surface 尚未初始化

Kotlin SurfaceView / lateinit property surface has not been initialized

提问人:doker797 提问时间:10/5/2023 最后编辑:dan1stdoker797 更新时间:10/5/2023 访问量:49

问:

我仍然很青涩,不知道该语言的一些功能。我在这里遇到以下问题是我的代码:

private lateinit var surface: SurfaceView
private var _binding: FragmentItem2Binding? = null
private val binding get() = _binding!!

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
    ): View? {
    _binding = FragmentItem2Binding.inflate(inflater, container, false)
    return binding.root

     }


override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    surface?.findViewById<SurfaceView>(R.id.surf)
        this.surface!!.holder!!.addCallback(object : SurfaceHolder.Callback {
            override fun surfaceCreated(holder: SurfaceHolder) {
               TODO("Not yet implemented")
            }

            override fun surfaceChanged(
               holder: SurfaceHolder,
               format: Int,
               width: Int,
               height: Int,
            ) {
               TODO("Not yet implemented")
            }

            override fun surfaceDestroyed(holder: SurfaceHolder) {
               TODO("Not yet implemented")
            }
        })

xml格式:

\<SurfaceView
    android:layout_width="400sp"
    android:layout_height="400sp"
    android:id="@+id/surf"
\\\>

如果我把:

lateinit var

它给出:

kotlin.UninitializedPropertyAccessException: lateinit property surface has not been initialized

如果我把:

private var surface: SurfaceView? = null

它给出了错误:java.lang.NullPointerException

我该怎么办?

Android kotlin nullpointerexception SurfaceView lateinit

评论

0赞 TheLibrarian 10/5/2023
您没有在任何地方设置。我想你的意思是打电话?surfaceViewbinding.surf
0赞 doker797 10/5/2023
我想做:surface = findViewById<SurfaceView>(R.id.surf) ,但我得到了:未解析的引用:findViewById。我需要访问覆盖函数,暂时,如果我正确理解了问题,我不需要 binding.surf。

答:

0赞 Kristy Welsh 10/5/2023 #1

您没有在任何地方初始化该值。尝试:

surface = findViewById<SurfaceView>(R.id.surf)

或在 viewBinding 中:

surface - viewBinding.surf //or what ever the id of the surface is

评论

0赞 doker797 10/5/2023
问题是在编写时: surface = findViewById<SurfaceView>(R.id.surf) 我得到: 未解析的引用:findViewById
0赞 doker797 10/5/2023 #2

我找到了一种运行它的方法:
surface = view.findViewById(R.id.surf) 有必要移动表达式以覆盖有趣的 onViewCreated 视图在哪里。 对不起,浪费你的时间,现在我的问题似乎很愚蠢)

评论

0赞 Community 10/16/2023
正如目前所写的那样,你的答案尚不清楚。请编辑以添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。您可以在帮助中心找到有关如何写出好答案的更多信息。