当前位置: 首页 > 知识库问答 >
问题:

将Fragment与制表符一起使用。指定的子级已具有父级

从经略
2023-03-14

我正在使用3个标签构建一个像WhatsApp一样的应用程序,每个标签都有一个< code >片段。在我的第一个< code >片段中,我有一个< code > recycle view 。

赢取一套SectionsPager适配器,开始宽度Recy,如下图所示:

inner class SectionsPagerAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm) {

        override fun getItem(position: Int): Fragment {
            // getItem is called to instantiate the fragment for the given page.
            // Return a PlaceholderFragment (defined as a static inner class below).
            //return PlaceholderFragment.newInstance(position + 1)
            when(position){
                0 ->  return Fragmenttask.newInstance()
                1 ->  return FragmentChat.newInstance()
                2 ->  return FragmentMaps.newInstance()
                else  -> {
                    return null!!
                }
            }
        }

        override fun getCount(): Int {
            // Show 3 total pages.
            return 3
        }
    }

它给了我这个错误:

E/AndroidRuntime:致命异常:主进程:com.deraah.mohamed。deraahpro,PID:21993 java.lang.IllegalStateException:指定的子级已经有父级。必须首先对孩子的父级调用removeView()。位于android.support.v4.view.ViewPager.addView(ViewPager.java:1477)的android.view.ViewGroup.addView(视图组java:4937),位于androids.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager java:1425)android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1740),位于android.support.v 4.app.BackStackRecord.executeOps(BackStack Record.java:794),位于Android.support.v4.app.碎片管理器Impl.execute Ops(碎片管理器.java:2580)android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2322),位于android/support.v 4.app.FragmentManager Impl.execSingleAction(Fragment Manager.java:2199),位于android.support.v4.app.BackStackRecord.commitNowAllowingStateLoss(BackStack Record.java:651),位于android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:662)位于android.support.v4.view.ViewPagerandroid.support.design.widget.TabLayout.dispatchTabSelected(TabLayer.java:1165)位于android/support.ddesign.wikit.TabLayout.selectTab(TabLayout.java:1158),位于androidsupport.destig.widget.Tab Layout.selectionTab(TabLayout_java:1128),位于android.support.design.widget.Tab2Layout$TabSelect(TabLayout.java:1537)位于android.view.view$PerformClick.run(view.java:24770),位于androids.os.Handler.handlerCallback(Handler.java:790),位于Android.os.Handler.dispatchMessage(Hanler.java:99),位于android.app.ActivityThread.main(ActivityThread.java:6494),位于java.lang.reflect.Method。在com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInite.java:438)在com.aandroid.iinternal.os.ZygoteInit.main(Zygote Init.java:807)调用(本机方法

更新

我的碎片:

聊天:

/**
 * A simple [Fragment] subclass.
 * Activities that contain this fragment must implement the
 * [FragmentChat.OnFragmentInteractionListener] interface
 * to handle interaction events.
 * Use the [FragmentChat.newInstance] factory method to
 * create an instance of this fragment.
 */
class FragmentChat : Fragment() {

    private var mListener: OnFragmentInteractionListener? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        return inflater!!.inflate(R.layout.fragment_fragment_chat, container, false)
    }

    // TODO: Rename method, update argument and hook method into UI event
    fun onButtonPressed(uri: Uri) {
        if (mListener != null) {
            mListener!!.onFragmentInteraction(uri)
        }
    }

    override fun onAttach(context: Context?) {
        super.onAttach(context)
    }

    override fun onDetach() {
        super.onDetach()
        mListener = null
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     *
     *
     * See the Android Training lesson [Communicating with Other Fragments](http://developer.android.com/training/basics/fragments/communicating.html) for more information.
     */
    interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        fun onFragmentInteraction(uri: Uri)
    }

    companion object {

        // TODO: Rename and change types and number of parameters
        fun newInstance(): FragmentChat {
            val fragment = FragmentChat()
            val args = Bundle()
            fragment.arguments = args
            return fragment
        }
    }
}// Required empty public constructor

片段映射:

/**
 * A simple [Fragment] subclass.
 * Activities that contain this fragment must implement the
 * [FragmentMaps.OnFragmentInteractionListener] interface
 * to handle interaction events.
 * Use the [FragmentMaps.newInstance] factory method to
 * create an instance of this fragment.
 */
class FragmentMaps : Fragment() {

    private var mListener: OnFragmentInteractionListener? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        return inflater!!.inflate(R.layout.fragment_fragment_maps, container, false)
    }

    // TODO: Rename method, update argument and hook method into UI event
    fun onButtonPressed(uri: Uri) {
        if (mListener != null) {
            mListener!!.onFragmentInteraction(uri)
        }
    }

    override fun onDetach() {
        super.onDetach()
        mListener = null
    }


    interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        fun onFragmentInteraction(uri: Uri)
    }

    companion object {
        // TODO: Rename and change types and number of parameters
        fun newInstance(): FragmentMaps {
            val fragment = FragmentMaps()
            val args = Bundle()
            fragment.arguments = args
            return fragment
        }
    }
}// Required empty public constructor

片段任务:

class Fragmenttask : Fragment() {

    private var mListener: OnFragmentInteractionListener? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        val CustumViewtask = inflater!!.inflate(R.layout.fragment_fragmenttask, container, false)
        val taskMainRV = CustumViewtask.findViewById(R.id.recyclerView_main) as RecyclerView
        //taskMainRV.setBackgroundColor(Color.BLUE)

        taskMainRV.layoutManager = LinearLayoutManager(context)
        //recyclerView_main.adapter = MainAdapter()

        fetchJson(taskMainRV)

        return taskMainRV
    }

    fun fetchJson(RSV: RecyclerView) {

        //SharedPreferences
        val MY_APP_INFO: String = "UserInfo"
        val prefs = activity.getSharedPreferences(MY_APP_INFO, AppCompatActivity.MODE_PRIVATE)
        val LoggedUserId = prefs.getString("UserId", null)
        println("your code is : $LoggedUserId")

        println("Attempting to Fetch JSON")

        val url = "http://Restful.com/get_tasks.php"

        val client = OkHttpClient()

        val formBody = FormBody.Builder().add("UserId", LoggedUserId).build()

        val request = Request.Builder().url(url)
                .post(formBody)
                .build()

        client.newCall(request).enqueue(object: Callback {
            override fun onResponse(call: Call?, response: Response?) {
                val body = response?.body()?.string()
                println("mohamed : $body")

                val gson = GsonBuilder().create()

                val tasksfeed = gson.fromJson(body, M_tasksFeed::class.java)

                activity.runOnUiThread {
                    RSV.adapter = MainAdaptertasks(tasksfeed)
                }

            }

            override fun onFailure(call: Call?, e: IOException?) {
                println("Failed to execute request")
            }
        })
    }

    // TODO: Rename method, update argument and hook method into UI event
    fun onButtonPressed(uri: Uri) {
        if (mListener != null) {
            mListener!!.onFragmentInteraction(uri)
        }
    }

    override fun onDetach() {
        super.onDetach()
        mListener = null
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     *
     *
     * See the Android Training lesson [Communicating with Other Fragments](http://developer.android.com/training/basics/fragments/communicating.html) for more information.
     */
    interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        fun onFragmentInteraction(uri: Uri)
    }

    companion object {
        fun newInstance(): Fragmenttask {
            val fragment = Fragmenttask()
            val args = Bundle()
            fragment.arguments = args
            return fragment
        }
    }
}// Required empty public constructor

共有3个答案

宋安晏
2023-03-14

问题来自

       else  -> {
                return null!!
            }

试试这种方式

override fun getItem(position: Int): android.support.v4.app.Fragment {

        // getItem is called to instantiate the fragment for the given page.
        // Return a PlaceholderFragment (defined as a static inner class below).
        //return PlaceholderFragment.newInstance(position + 1)
       var fragment: android.support.v4.app.Fragment? = null
       when (position) {
           0 -> fragment = Fragmenttask.newInstance()
           1 -> fragment = FragmentChat.newInstance()
           2 -> fragment = FragmentMaps.newInstance()
       }

       return fragment!!
   }

   override fun getCount(): Int {
       return 3           //no of cases/fragments
   }

}

< code >仅供参考

您必须调用 removeView()

每个片段部分

 View viewOBJ = inflater.inflate(R.layout.layout_child, parent_layout, false);

  return viewOBJ ;
封弘伟
2023-03-14

您确定在膨胀片段视图时将attachRootView设置为false了吗?

inflater.inflate(R.layout.fragment, container, false)
傅经业
2023-03-14

您返回了错误的视图签入Fragmenttask

使用这个

 return CustumViewtask

取而代之的是这个

return taskMainRV

像这样更改代码

override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        val CustumViewtask = inflater!!.inflate(R.layout.fragment_fragmenttask, container, false)
        val taskMainRV = CustumViewtask.findViewById(R.id.recyclerView_main) as RecyclerView
        //taskMainRV.setBackgroundColor(Color.BLUE)

        taskMainRV.layoutManager = LinearLayoutManager(context)
        //recyclerView_main.adapter = MainAdapter()

        fetchJson(taskMainRV)

        return CustumViewtask
    }
 类似资料:
  • 问题内容: 在我的应用中,我必须经常在两种布局之间切换。错误在下面发布的布局中发生。 第一次调用布局时,没有发生任何错误,一切都很好。然后,当我调用不同的布局(空白),然后再次调用我的布局时,出现以下错误: 我的布局代码如下所示: 我知道之前曾有人问过这个问题,但对我来说没有帮助。 问题答案: 错误消息说明你应该做什么。

  • 我必须经常在两种布局之间切换。错误发生在下面发布的布局中。 第一次调用我的布局时,没有发生任何错误,一切正常。然后,当我调用另一个布局(空白布局)并再次调用我的布局时,它抛出以下错误: 我的布局代码如下所示: 我知道以前有人问过这个问题,但对我来说没有帮助。

  • 有人能帮我吗?我不知道为什么我会犯这个错误。

  • 我试图做一个问答应用程序,在那里你点击加号按钮来添加一个问答。屏幕上弹出一个按钮,你可以点击它来播放或编辑测验。当我点击新创建的按钮一次很好,但第二次点击它时,应用程序崩溃了。有人知道我如何专门修复这个错误吗? 2020-12-28 13:48:47.521 266 48-26648/com.example.k_ari E/AndroidRuntime:致命异常:main process:com.

  • 问题内容: 由生成的解析器表现出以下有趣的行为,这阻止了我编写模式来解析字符串,例如: 我调试了代码,似乎问题是由年份字段解析超出了字符串的末尾引起的(三个y的最大宽度始终为19)。但是,我不明白如果没有最后的文字,它如何对模式起作用。 有什么办法可以不必使用格式化程序生成器来解决此问题? 编辑: 由于下面的Jarrod确认这是越野车,因此我进行了更多的谷歌搜索,最后找到了错误报告: http:/

  • 我正在尝试将数据提供给我的listView,单击FAB时,它会显示一个对话框,其中包含一个editText和两个按钮。在第一次,它允许我向ListView提供数据。但是当我第二次尝试时,它会显示错误: FATAL EXCEPTION: main Process:com.example.app.wounderlist.wounderlist.HomeFragment, PID: 3790 1.onC