如何使用kotlin片段

时间:2017-06-19 18:22:59

标签: android android-fragments kotlin kotlin-android-extensions

我找不到如何使用kotlin使用片段。 我在onCreateView方法中遇到错误,请帮助我。

ListaFragment.kt:

class ListaFragment : Fragment() {

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle): View? {
    val view = inflater.inflate(R.layout.fragment_lista, container, false)

    return view
}
}

fragment_lista.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAlignment="center"
        android:text="Hello"/>
</LinearLayout>

MainActivity.kt:

class MainActivity : AppCompatActivity() {

    private var listaFragment: ListaFragment? = null
    override fun onCreate(savedState: Bundle?) {
        super.onCreate(savedState) //cual es la diferencia con savedInstanceState
        setContentView(R.layout.activity_main)

        listaFragment = Fragment.instantiate(this@MainActivity,
                ListaFragment::class.java!!.getName()) as ListaFragment

        fragmentManager.beginTransaction().replace(R.id.flLista, listaFragment).commit()
    }
}

activity_main.xml中:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.harol.appfinalandroid.MainActivity">

    <FrameLayout
        android:id="@+id/flLista"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></FrameLayout>

</LinearLayout>

我没有语法错误,当我打开片段时应用程序停止

错误:

Caused by: java.lang.IllegalArgumentException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkParameterIsNotNull, parameter savedInstanceState
                                                                                     at com.example.harol.appfinalandroid.ListaFragment.onCreateView(ListaFragment.kt:0)

2 个答案:

答案 0 :(得分:14)

savedInstanceState可以为空,但您将其声明为Bundle - 它应为Bundle?

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?): View? {

答案 1 :(得分:2)

我也遇到过这个问题,直到我找到它为止,这让我很生气。

onCreateView中,您需要使savedInstanceState像这样可以为空:

savedInstanceState: Bundle?(添加问号以表明它可以为空)