我正在尝试从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);
转换为科特林后
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 TextView
和val miwokTextView= listView!!.findViewById(R.id.miwok_text_view) as TextView
,但是在findViewById上仍然出现错误 最佳答案
得到它了
val miwokTextView = listView?.findViewById <
View >
(R.id.miwok_text_view)作为TextView