首页 文章

错误:错误:在View类型的可空接收器上只允许安全(? . )或非空断言(!! . )调用?

提问于
浏览
0

我正在尝试将一些代码从Java编码到kotlin,但我一直在搞这个foll错误

错误:错误:在View类型的可空接收器上只允许安全(? . )或非空断言(!! . )调用?

Java代码

View listItemView = convertView;
        if (listItemView == null) {
            listItemView = LayoutInflater.from(getContext()).inflate(
                    R.layout.list_item, parent, false);
        }

        // Get the {@link Word} object located at this position in the list
        Word currentWord = getItem(position);

        // Find the TextView in the list_item.xml layout with the ID miwok_text_view.
        TextView miwokTextView = (TextView) listItemView.findViewById(R.id.miwok_text_view);

转换为kotlin后

var listView:View? =convertView
        if(listView==null){
            listView=LayoutInflater.from(context).inflate(R.layout.list_item,parent,false)
        }

        var currentWord:Word=getItem(position)

        val miwokTextView= listView.findViewById(R.id.miwok_text_view) as TextView

我在listView.findViewById得到错误,即使包括?或!!,错误不会消失 . 我甚至尝试从JetBrains的在线转换器,当我将转换后的代码粘贴到Android工作室时,我仍然不断收到错误 . 请帮助

我尝试了 val miwokTextView= listView?.findViewById(R.id.miwok_text_view) as TextViewval miwokTextView= listView!!.findViewById(R.id.miwok_text_view) as TextView ,但我仍然在findViewById收到错误

2 回答

  • 0

    知道val miwokTextView = listView?.findViewById < 查看 > (R.id.miwok_text_view)作为TextView

  • 1

    将类型 val 更改为 var ,如此格式 . 因为val不能重新分配 .

    var miwokTextView= listView?.findViewById<View>(R.id.miwok_text_view) as TextView
    

相关问题