将findViewById从Java转换为Kotlin

时间:2020-03-16 15:25:19

标签: java android 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中为每个变量分配回收者视图?

2 个答案:

答案 0 :(得分:2)

我认为,变革的夫妇将奏效。

删除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 library

编辑

Anko已弃用see

答案 1 :(得分: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!"
}