Convert findViewById from Java to Kotlin

Babbara :

I'm trying to convert this piece of code from 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;
}

to Kotlin:

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
}

The problem is that the compiler does not recognize the findViewById. How can I assign the recycler view in my xml to each variable?

TemaTre :

According to this https://antonioleiva.com/kotlin-android-extensions/ You did not need in method "findViewById". Currently you can use name as a field of class. For example

<?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>

And now you can use welcomeMessage like this

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    welcomeMessage.text = "Hello Kotlin!"
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=291050&siteId=1