我不明白为什么Kotlin给我这个错误:夸大类片段的错误 这是一个非常简单的片段中的代码
MainActivityFragment
import android.support.v4.app.Fragment
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.fragment_main.*
/**
* A placeholder fragment containing a simple view.
*/
class MainActivityFragment : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
text.text = "test2"
return inflater.inflate(R.layout.fragment_main, container, false)
}
}
fragment_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivityFragment"
tools:showIn="@layout/activity_main">
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
我在哪里做错了?
答案 0 :(得分:3)
您不能在之前给文本分配片段大小。首先在onCreateView上填充片段,然后在onCreate方法上添加文本
答案 1 :(得分:1)
在使用视图之前,需要先使其膨胀。将您的代码移至onViewCreated
事件:
class MainActivityFragment : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_main, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
text.text = "test2"
}
}