在运行时添加片段与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中
希望这可以帮助。
- kotlin.TypeCastException:null不能转换为非空类型com.midsizemango.databasekotlin.Note
- 使用Anko更改按钮文本和进度条颜色
- 在处理kotlin中的getter和setter时出错
- SimpleXML在Thread.getContextClassLoader()返回的类加载器可能失败之后抛出ClassNotFoundException
- Android构建失败,kotlin-reflect和proguard
- 在android中加载页面加载firebase数据
- 使用Kotlin在Android中添加数字
- 未解决的参考:LinearLayoutManager / RecyclerView
- Kotlin当多个值不工作时值是一个Android视图