我正在尝试从Java转换这段代码:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.main_fragment, container, false);
genre[0] = view.findViewById(R.id.MovieGenre);
genre[1] = view.findViewById(R.id.MovieGenre2);
genre[2] = view.findViewById(R.id.MovieGenre3);
recyclerView[0] = view.findViewById(R.id.rc_view);
recyclerView[1] = view.findViewById(R.id.rc_view2);
recyclerView[2] = view.findViewById(R.id.rc_view3);
if (movieList.size()==0) loadMovie();
else refreshList();
return view;
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
view = inflater.inflate(R.layout.main_fragment, container, false) as Nothing?
genre[0] = this.view.findViewById(R.id.MovieGenre)
genre[1] = this.view.findViewById(R.id.MovieGenre2)
genre[2] = view.findViewById(R.id.MovieGenre3)
recyclerView[0] = view.findViewById(R.id.rc_view)
recyclerView[1] = view.findViewById(R.id.rc_view2)
recyclerView[2] = view.findViewById(R.id.rc_view3)
if (movieList.size == 0) loadMovie() else refreshList()
return view
}
问题是编译器无法识别findViewById。如何在xml中为每个变量分配回收者视图?
问题来源:Stack Overflow
根据此https://antonioleiva.com/kotlin-android-extensions/, 您无需在方法“ findViewById”中使用。当前,您可以将名称用作类的字段。例如
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/welcomeMessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!"/>
</FrameLayout>
现在您可以像这样使用welcomeMessage
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
welcomeMessage.text = "Hello Kotlin!"
}
回答来源:Stack Overflow
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。