将Fragment与制表符一起使用..指定的子节点已有父节点

时间:2018-03-19 07:34:15

标签: android kotlin

我使用3个标签构建类似WhatsApp的应用,每个标签都有Fragment。在我的第一个Fragment中,我有RecyclerView

赢取一套SectionsPagerAdapter以开始使用RecyclerView Fragment的宽度 像这样:

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.view.ViewGroup.addViewInner(ViewGroup.java:4937)                                                                                 在android.view.ViewGroup.addView(ViewGroup.java:4768)                                                                                 在android.support.v4.view.ViewPager.addView(ViewPager.java:1477)                                                                                 在android.view.ViewGroup.addView(ViewGroup.java:4708)                                                                                 在android.view.ViewGroup.addView(ViewGroup.java:4681)                                                                                 在   android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1425)                                                                                 在   android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1740)                                                                                 在   android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:794)                                                                                 在   android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2580)                                                                                 在   android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2367)                                                                                 在   android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2322)                                                                                 在   android.support.v4.app.FragmentManagerImpl.execSingleAction(FragmentManager.java:2199)                                                                                 在   android.support.v4.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:651)                                                                                 在   android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:145)                                                                                 在android.support.v4.view.ViewPager.populate(ViewPager.java:1236)                                                                                 在   android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:662)                                                                                 在   android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:624)                                                                                 在   android.support.v4.view.ViewPager.setCurrentItem(ViewPager.java:605)                                                                                 在   android.support.design.widget.TabLayout $ ViewPagerOnTabSelectedListener.onTabSelected(TabLayout.java:2170)                                                                                 在   android.support.design.widget.TabLayout.dispatchTabSelected(TabLayout.java:1165)                                                                                 在   android.support.design.widget.TabLayout.selectTab(TabLayout.java:1158)                                                                                 在   android.support.design.widget.TabLayout.selectTab(TabLayout.java:1128)                                                                                 在   android.support.design.widget.TabLayout $ Tab.select(TabLayout.java:1427)                                                                                 在   android.support.design.widget.TabLayout $ TabView.performClick(TabLayout.java:1537)                                                                                 在android.view.View $ PerformClick.run(View.java:24770)                                                                                 在android.os.Handler.handleCallback(Handler.java:790)                                                                                 在android.os.Handler.dispatchMessage(Handler.java:99)                                                                                 在android.os.Looper.loop(Looper.java:164)                                                                                 在android.app.ActivityThread.main(ActivityThread.java:6494)                                                                                 at java.lang.reflect.Method.invoke(Native Method)                                                                                 在   com.android.internal.os.RuntimeInit $ MethodAndArgsCaller.run(RuntimeInit.java:438)                                                                                 在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

更新

我的片段:

FragmentChat:

/**
 * 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

FragmentMaps:

/**
 * 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

Fragmenttask:

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 个答案:

答案 0 :(得分:1)

您错误view检入 Fragmenttask Fragment

使用此

 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
    }

答案 1 :(得分:0)

来自

的问题
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="btn btn-success btn-sm view-profile" data-citizens='{ "id" : 1}'> Profile</button>

试试这种方式

       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 } }

您必须致电removeView()

每个片段部分

FYI

答案 2 :(得分:0)

您是否确定在展开片段视图时已将attachRootView设置为false?

inflater.inflate(R.layout.fragment, container, false)