繁体   English   中英

将 findViewById 从 Java 转换为 Kotlin

[英]Convert findViewById from Java to 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 中的回收器视图分配给每个变量?

我想,有一些变化会奏效。

删除as Nothing?

view = inflater.inflate(R.layout.main_fragment, container, false) as Nothing?

那可能是不必要的。

我不明白你在初始化像genre[0], genre[1] ..

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)

相反,您可以尝试如下

val recycler_view = findViewById<RecyclerView>(R.id.recycler_view)

或者

val recycler_view: RecyclerView = findViewById(R.id.recycler_view)

或者您可以尝试@TemaTre 答案中提到的扩展功能。

或者 你可以使用 anko 库

编辑

Anko 已弃用,请参阅

根据这个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!"
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM