开发者社区> 问答> 正文

将findViewById从Java转换为Kotlin

我正在尝试从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

展开
收起
montos 2020-03-22 14:09:45 1312 0
1 条回答
写回答
取消 提交回答
  • 根据此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

    2020-03-22 14:10:34
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载