首页 > 解决方案 > How to use Fragments dynamically, within another Fragment

问题描述

I'm developing an app in android (sdk 27) I have to create an entry data layout that should be dynamic. So i think in fragments. First I already have 3 tabs (general,detail,comments), and I want to make "detail" tab content variable. I have 3 layouts for this tabs.

I already created 2 fragments, but when I run the program I get this error:

Process: ar.com.codigose.atmobile, PID: 13014
    java.lang.RuntimeException: ar.com.codigose.atmobile.CargaDataEnsayoActivity@89c8433 must implement OnFragmentInteractionListener
        at ar.com.codigose.atmobile.CobbFragment.onAttach(CobbFragment.java:86)
...
...

The question is: do I have to add : OnFragmentInteractionListener on the main activity (the activity that manage tabs)? Or there is another way ?

The idea is that i will change programmatically ( with a spinner ), the fragment in "Details" Tab, so I think I don't need to add that listener...

this is the layout where I want to change programmatically the fragment:

fragment_repeticion_enfermedad_var.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".RepeticionEnfermedadVarFragment">

    <!-- TODO: Update blank fragment layout -->

    <TextView
        android:id="@+id/tv_enfermedad"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello_blank_fragment"
        android:textSize="18sp"
        android:textStyle="bold" />

    <Spinner
        android:id="@+id/spinner_enfermedad"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:drawable/spinner_dropdown_background" />

    <FrameLayout
        android:id="@+id/frag_enfermedad"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </FrameLayout>

</LinearLayout>

this is how I'll make dynamic change of Fragments.

...
Fragment fragment = new CobbFragment(); // Luego seria variable
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.replace(R.id.frag_enfermedad, fragment).commit();
...

I use getChildFragmentManager() because I read that is needed when you want to use fragments in another fragment.

Any suggestion ?

Best Regards

标签: androidandroid-fragments

解决方案


您应该OnFragmentInteractionListenerCargaDataEnsayoActivity课堂上实施或删除onAttach片段的此签入


推荐阅读