由于:kotlin.TypeCastException: null 无法转换为非空类型 android.widget.TextView 在片段中。

3
class DashBoardFragment : Fragment() {

    private var recyclerView : RecyclerView?=null


    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        var view = inflater!!.inflate(R.layout.fragment_dash_board, container, false)

        initComponents(view )


            return  view
        }

        private fun initComponents(View view) {



            var textView : TextView = view?.findViewById(R.id.recyclerView) as TextView
            textView.setText("hello world")  
    } 

当转换为回收站时,显示相同的问题,如果您能帮助我解决这个问题,我将不胜感激。

好吧,请添加更多细节。比如,你想要完成什么,你是怎么做的,你在这种方法中遇到了什么困难,你尝试过哪些其他方法等等。总之,没有代码不是一个好问题, 只有代码也不是。寻找平衡!


如果您认为某个答案解决了您的问题,您应该通过点击帖子旁边的勾号接受它。 - Sriram Kailasam
1个回答

4

尝试将initComponents函数中的代码移动到onCreateView函数中。可能会出现错误,因为recyclerView id在View创建之前还没有准备好。

override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        var view = inflater!!.inflate(R.layout.fragment_dash_board, container, false)

        var textView : TextView = view?.findViewById(R.id.recyclerView) as TextView
        textView.setText("hello world")


        return  view
    }

谢谢,它正常工作了,但我不知道问题出在哪里。当我创建新函数并从中调用时,它无法正常工作。 - Tarun konda
onCreateView 方法在视图创建时被调用。您必须在此方法中初始化片段的所有视图,否则它们将被设置为 null。这就是为什么在 initComponents 方法中无法正常工作的原因。 - Sriram Kailasam

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接