簡體   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