var mainFragment: NeedsFragment? = null
supportFragmentManager.beginTransaction().add(R.id.container, mainFragment!!)
.commit()
我正在尝试从活动中打开片段,但是应用崩溃导致无法打开活动的错误。
如何在Kotlin中做到这一点?
答案 0 :(得分:0)
var mainFragment: NeedsFragment = NeedsFragment()
supportFragmentManager.beginTransaction().add(R.id.container, mainFragment)
.commit()
oncreate之外。
class frag : NeedsFragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// replace if you already have a layout
return inflater.inflate(R.layout.frag, container, false)
}
}
示例frag.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal|center_vertical"
android:orientation="vertical">
<TextView
android:id="@+id/txtView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
</LinearLayout>
答案 1 :(得分:0)
我认为您应该先创建片段,然后将其放置为空,而不是将其设置为空:
var mainFragment : NeedsFragment = NeedsFragment()