在运行时添加片段与Kotlin原因“不幸的应用程序已停止”

我是新的Kotlin,我试图在运行时运行片段,但我的应用程序崩溃消息“不幸的应用程序已停止”

这是我的片段kotlin类:

import android.os.Bundle import android.support.v4.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup class TestFragment : Fragment() { override fun onCreateView (inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater?.inflate(R.layout.test_fragment, container, false) } } 

框架布局与:

 <FrameLayout 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:id="@+id/testFragment" android:layout_width="match_parent" android:layout_height="match_parent"> 

这是我的活动:

 import android.annotation.SuppressLint import android.os.Bundle import android.support.v4.app.Fragment import android.support.v7.app.AppCompatActivity import kotlinx.android.synthetic.main.activity_display_text.* class DisplayText : AppCompatActivity() { @SuppressLint("ResourceType") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_display_text) var toDisplay = intent.extras.get("MainActivity_HELLO_WORLD") displayText.text = toDisplay as String if(R.id.testFragment !== null) { if(savedInstanceState !== null) { return } val fragment = TestFragment() getSupportFragmentManager().beginTransaction() .add(R.id.testFragment, fragment).commit() } } } 

你能告诉我我做错了什么吗?

这个方法调用是错误的:

 getSupportFragmentManager().beginTransaction().add(R.id.testFragment, fragment).commit() 

因为add方法的第一个参数应该是你的片段容器(你的活动中将接收frament的布局)。

这里你试图通过你的片段的布局,这不是当前膨胀的视图层次的一部分。 所以FragmentManager在视图层次结构中寻找一个不存在的视图,并崩溃。

你需要传递一个有效的ViewGroup的id。 我们通常使用一个FrameLayout作为一个片段容器。 而这个容器需要包含在你的activity的layout.xml中

希望这可以帮助。