膨胀 class 片段 Android 时出错 Studio Kotlin

Error inflating class fragment Android Studio Kotlin

我想将数据从 activity 传输到片段,但我收到“错误膨胀 class 片段”我已经搜索了该问题的解决方案,但仍然找不到。

这是我FirstFragment.kt

的完整代码
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment

// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"

/**
 * A simple [Fragment] subclass.
 * Use the [FirstFragment.newInstance] factory method to
 * create an instance of this fragment.
 */
class FirstFragment : Fragment() {
    // TODO: Rename and change types of parameters
    private var param1: String? = null
    private var param2: String? = null
    private lateinit var communicator: Communicator
    private lateinit var myTextView: TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            param1 = it.getString(ARG_PARAM1)
            param2 = it.getString(ARG_PARAM2)
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        val view = inflater.inflate(R.layout.fragment_first, container, false)
        myTextView = view.findViewById<View>(R.id.profile_name_text) as TextView

        // Gets the data from the passed bundle
        val bundle = arguments
        val message = bundle!!.getString("mText")

        // Sets the derived data (type String) in the TextView
        myTextView.text = message
        return view
    }

    companion object {
        /**
         * Use this factory method to create a new instance of
         * this fragment using the provided parameters.
         *
         * @param param1 Parameter 1.
         * @param param2 Parameter 2.
         * @return A new instance of fragment FirstFragment.
         */
        // TODO: Rename and change types and number of parameters
        @JvmStatic
        fun newInstance(param1: String, param2: String) =
            FirstFragment().apply {
                arguments = Bundle().apply {
                    putString(ARG_PARAM1, param1)
                    putString(ARG_PARAM2, param2)
                }
            }
    }
}

我的函数在 Home.kt

fun getData() {
    val mFragmentManager = supportFragmentManager
    val mFragmentTransaction = mFragmentManager.beginTransaction()
    val mFragment = FirstFragment()
    val mBundle = Bundle()
    val testText = "My Name is Jack"
    mBundle.putString("mText",testText)
    mFragment.arguments = mBundle
    mFragmentTransaction.add(R.id.fragmentContainerView, mFragment).commit()
}

fragment_first.xml 我想将文本放入 TextView

<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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=".Home">
<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:id="@+id/linear_Layout_home_1"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:layout_marginTop="30dp"
        android:layout_marginStart="15dp"
        android:layout_marginEnd="15dp"
        android:paddingStart="15dp"
        android:paddingEnd="15dp"
        android:paddingTop="10dp"
        android:orientation="horizontal"
        android:background="@drawable/rounded_blue_shape"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent">


            <TextView
                android:id="@+id/profile_name_text"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="@string/nama_pengguna"
                android:textStyle="bold"
                android:textSize="15sp"
                android:textColor="@color/cloudy"/>
    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>
</ScrollView>

这是activity_home.xml

的代码
<androidx.constraintlayout.widget.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=".Home">

        <com.google.android.material.bottomnavigation.BottomNavigationView
            android:id="@+id/bottom_navigation"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:menu="@menu/navigation"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"/>


    <fragment
        android:id="@+id/fragmentContainerView"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:navGraph="@navigation/my_nav"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

有人可以帮我吗?

您可以像这样使用片段构造函数传递数据:

fun getData() {

   val mFragmentManager = supportFragmentManager
   val mFragmentTransaction = mFragmentManager.beginTransaction()
   val testText = "My Name is Jack"
   val mFragment = FirstFragment(testText)
   mFragmentTransaction.add(R.id.fragmentContainerView, mFragment).commit()
}

然后像这样在片段中获取它:

class FirstFragment(private val someText: String): Fragment() {

    private lateinit var myTextView: TextView

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        val view = inflater.inflate(R.layout.fragment_first, container, false)
        myTextView = view.findViewById<View>(R.id.profile_name_text) as TextView

        // Sets the derived data (type String) in the TextView
        myTextView.text = someText
        return view
    }
}

同时看到你的 fragment_first.xml 布局,你可能想这样写:

<RelativeLayout 
    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">

        <TextView
            android:id="@+id/profile_name_text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/nama_pengguna"
            android:textStyle="bold"
            android:textSize="15sp"
            android:textColor="@color/cloudy"/>

</RelativeLayout>

不确定是什么导致了您的问题。但是注意到您正在使用 Jetpack 导航。

并且您正在尝试将数据传递到图表的起始目的地。

这是处理您的案例的官方文档: Pass data to the start destination.

下面是我自己尝试的一些代码,仅供参考:

我认为在你的 MainActivity.kt 中,你会有这样的东西:

        val navController = findNavController(R.id.fragmentContainerView)
        navController.setGraph(R.navigation.my_nav, Bundle().apply {
            putString("name", "My name is xx")
        })

然后在第一个片段中,检索参数:

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val name = arguments?.get("name")
        Log.w("xx", "$name")

编辑:我根据您代码中的 ID 更新了 findNavController(R.id.fragmentContainerView)navController.setGraph(R.navigation.my_nav

基于文档:

Note: when manually calling setGraph() with arguments, you must not use the app:navGraph attribute when creating the NavHostFragment in XML as that will internally call setGraph() without any arguments, resulting in your graph and start destination being created twice.

docs

您已经在 activity(片段容器)上定义了 app: navGraph,因此您不能从 java/kotlin 调用 navController. SetGraph。 尝试从 Fragment Container

中删除 app:navGraph