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

时间:2017-10-17 15:43:21

标签: java android kotlin

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

错误:错误:在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 studio时,我仍然不断收到错误。请帮忙

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

2 个答案:

答案 0 :(得分:1)

知道了  val miwokTextView = listView?.findViewById <>(R.id.miwok_text_view)视为TextView

答案 1 :(得分:0)

将此类型val更改为var。因为无法重新分配。

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