gpt4 book ai didi

java - 使用 Kotlin 在运行时添加 fragment 会导致 'Unfortunately app has stopped'

转载 作者:行者123 更新时间:2023-12-02 12:15:25 25 4
gpt4 key购买 nike

我是 Kotlin 新手,我正在尝试在运行时运行 fragment ,但我的应用程序崩溃并显示消息“不幸的是应用程序已停止”

这是我的 Fragment 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">

这是我的 Activity :

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 方法的第一个参数应该是您的 fragment 容器(您的 Activity 中将接收框架的布局)。

在这里,您尝试传递 fragment 的布局,该布局不属于当前膨胀的 View 层次结构的一部分。因此 FragmentManager 在 View 层次结构中查找不存在的 View ,然后崩溃了。

您需要向那里传递有效 ViewGroup 的 ID。我们通常使用 FrameLayout 作为 fragment 容器。并且这个容器需要包含在您的 Activity 的layout.xml 中

希望这有帮助。

关于java - 使用 Kotlin 在运行时添加 fragment 会导致 'Unfortunately app has stopped',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46221259/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com