¿Cómo transferir algunos datos a otro Fragmento?


194

Cómo transferir algunos datos a otro Fragmentdel mismo modo que se hizo con el extrasde intents?


Intento responder esta pregunta @ aquí . Espero que funcione.
— ozhanli

Respuestas:


482

Use a Bundle. Aquí hay un ejemplo:

Fragment fragment = new Fragment();
Bundle bundle = new Bundle();
bundle.putInt(key, value);
fragment.setArguments(bundle);

Bundle ha puesto métodos para muchos tipos de datos. Ver esto

Luego, en su Fragment, recupere los datos (por ejemplo, en el onCreate()método) con:

Bundle bundle = this.getArguments();
if (bundle != null) {
        int myInt = bundle.getInt(key, defaultValue);
}

1
Hola, gracias por su respuesta, pero ¿necesitamos implementar algo como Serializable o Parcelable?
— Ankit Srivastava

No, no necesita implementar ninguna clase.
— Gene

2
¡Es posible que desee agregar un cheque para ver ese paquete! = ¿Nulo antes de intentar sacar algo de él?
— Niels

¿Y si tienes un fragmento existente en la memoria?
— polvo366

este código no funciona, no redirige la actividad a fragmentos con datos
— Venkatesh

44

Para ampliar aún más la respuesta anterior, como decía Ankit, para los objetos complejos debe implementar Serializable. Por ejemplo, para el objeto simple:

public class MyClass implements Serializable {
    private static final long serialVersionUID = -2163051469151804394L;
    private int id;
    private String created;
}

En ti FromFragment:

Bundle args = new Bundle();
args.putSerializable(TAG_MY_CLASS, myClass);
Fragment toFragment = new ToFragment();
toFragment.setArguments(args);
getFragmentManager()
    .beginTransaction()
    .replace(R.id.body, toFragment, TAG_TO_FRAGMENT)
    .addToBackStack(TAG_TO_FRAGMENT).commit();

en su ToFragment:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

    Bundle args = getArguments();
    MyClass myClass = (MyClass) args
        .getSerializable(TAG_MY_CLASS);

Eres el mejor
— hash

1
@Sameera Normalmente solo pongo una cadena con mi clase de fragmento, es decir, si tengo la clase MyFragmentIMGoingTo.java, entonces mi TAG_TO_FRAGMENT = "MyFragmentIMGoingTo";
— mike.tihonchik

Mejor uso Parcelable ya que Google lo recomendó como una técnica de serialización más optimizada para el sistema operativo Android.
— Gema

16

getArguments () está volviendo nulo porque "No obtiene nada"

Pruebe este código para manejar esta situación.

if(getArguments()!=null)
{
int myInt = getArguments().getInt(key, defaultValue);
}

Hola, gracias por su respuesta, pero ¿necesitamos implementar algo como Serializable o Parcelable?
— Ankit Srivastava

¿estás seguro? porque tuve que implementar Serializable / Parcelable cuando pasaba datos complejos entre un fragmento y una actividad usando la intención ......
— Ankit Srivastava

Lo intenté solo con valores simples. No tengo idea de Serializable o Parcelable lo siento
— Sakthimuthiah

1
¡Debería ser un comentario, no una respuesta!
— Gema

14

Código completo de paso de datos usando fragmento a fragmento

Fragment fragment = new Fragment(); // replace your custom fragment class 
Bundle bundle = new Bundle();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
                bundle.putString("key","value"); // use as per your need
                fragment.setArguments(bundle);
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.replace(viewID,fragment);
                fragmentTransaction.commit();

En clase de fragmento personalizado

Bundle mBundle = new Bundle();
mBundle = getArguments();
mBundle.getString(key);  // key must be same which was given in first fragment

¿Dónde obtener viewID?
— Hoo

@Hoo: por favor especifique su pregunta qué quiere hacer
— Anand Savjani


5

Solo para extender las respuestas anteriores, podría ayudar a alguien. Si getArguments()regresa null, póngalo en onCreate()método y no en constructor de su fragmento:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    int index = getArguments().getInt("index");
}

1
            First Fragment Sending String To Next Fragment
            public class MainActivity extends AppCompatActivity {
                    private Button Add;
                    private EditText edt;
                    FragmentManager fragmentManager;
                    FragClass1 fragClass1;


                    @Override
                    protected void onCreate(Bundle savedInstanceState) {
                        super.onCreate(savedInstanceState);
                        setContentView(R.layout.activity_main);
                        Add= (Button) findViewById(R.id.BtnNext);
                        edt= (EditText) findViewById(R.id.editText);

                        Add.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                fragClass1=new FragClass1();
                                Bundle bundle=new Bundle();

                                fragmentManager=getSupportFragmentManager();
                                fragClass1.setArguments(bundle);
                                bundle.putString("hello",edt.getText().toString());
                                FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();
                                fragmentTransaction.add(R.id.activity_main,fragClass1,"");
                                fragmentTransaction.addToBackStack(null);
                                fragmentTransaction.commit();

                            }
                        });
                    }
                }
         Next Fragment to fetch the string.
            public class FragClass1 extends Fragment {
                  EditText showFrag1;


                    @Nullable
                    @Override
                    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

                        View view=inflater.inflate(R.layout.lay_frag1,null);
                        showFrag1= (EditText) view.findViewById(R.id.edtText);
                        Bundle bundle=getArguments();
                        String a=getArguments().getString("hello");//Use This or The Below Commented Code
                        showFrag1.setText(a);
                        //showFrag1.setText(String.valueOf(bundle.getString("hello")));
                        return view;
                    }
                }
    I used Frame Layout easy to use.
    Don't Forget to Add Background color or else fragment will overlap.
This is for First Fragment.
    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/activity_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:background="@color/colorPrimary"
        tools:context="com.example.sumedh.fragmentpractice1.MainActivity">

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/editText" />
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:id="@+id/BtnNext"/>
    </FrameLayout>


Xml for Next Fragment.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
   android:background="@color/colorAccent"
    android:layout_height="match_parent">
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/edtText"/>

</LinearLayout>

3
¿Explica tu respuesta? código sin ninguna explicación no será de mucha ayuda
— Codificador

He escrito código en un flujo para que se pueda entender ..... Transmitir datos de la actividad principal a FragClass1 con el uso del paquete.
— Sumedh Ulhe

1

De la clase de actividad:

Envíe los datos utilizando argumentos de paquete al fragmento y cargue el fragmento

   Fragment fragment = new myFragment();
   Bundle bundle = new Bundle();
   bundle.putString("pName", personName);
   bundle.putString("pEmail", personEmail);
   bundle.putString("pId", personId);
   fragment.setArguments(bundle);

   getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                    fragment).commit();

De la clase myFragment:

Obtenga los argumentos del paquete y configúrelos en xml

    Bundle arguments = getArguments();
    String personName = arguments.getString("pName");
    String personEmail = arguments.getString("pEmail");
    String personId = arguments.getString("pId");

    nameTV = v.findViewById(R.id.name);
    emailTV = v.findViewById(R.id.email);
    idTV = v.findViewById(R.id.id);

    nameTV.setText("Name: "+ personName);
    emailTV.setText("Email: "+ personEmail);
    idTV.setText("ID: "+ personId);

Lea la pregunta nuevamente, se trata de fragmento a fragmento
— Amin Pinjari

1

Así es como se usa el paquete:

Bundle b = new Bundle();
b.putInt("id", id);
Fragment frag= new Fragment();
frag.setArguments(b);

recuperar el valor del paquete:

 bundle = getArguments();
 if (bundle != null) {
    id = bundle.getInt("id");
 }

0

Su fragmento de entrada

public class SecondFragment extends Fragment  {


    EditText etext;
    Button btn;
    String etex;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.secondfragment, container, false);
        etext = (EditText) v.findViewById(R.id.editText4);
        btn = (Button) v.findViewById(R.id.button);
        btn.setOnClickListener(mClickListener);
        return v;
    }

    View.OnClickListener mClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {


            etex = etext.getText().toString();
            FragmentTransaction transection = getFragmentManager().beginTransaction();
            Viewfragment mfragment = new Viewfragment();
            //using Bundle to send data
            Bundle bundle = new Bundle();
            bundle.putString("textbox", etex);
            mfragment.setArguments(bundle); //data being send to SecondFragment
            transection.replace(R.id.frame, mfragment);
            transection.isAddToBackStackAllowed();
            transection.addToBackStack(null);
            transection.commit();

        }
    };



}

su fragmento de vista

public class Viewfragment extends Fragment {

    TextView txtv;
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.viewfrag,container,false);
        txtv = (TextView)  v.findViewById(R.id.textView4);
        Bundle bundle=getArguments();
        txtv.setText(String.valueOf(bundle.getString("textbox")));
        return v;
    }


}

0

Si está utilizando el gráfico para la navegación entre fragmentos, puede hacer esto: Desde el fragmento A:

    Bundle bundle = new Bundle();
    bundle.putSerializable(KEY, yourObject);
    Navigation.findNavController(view).navigate(R.id.contactExtendedFragment, bundle);

Para fragmentar B:

    Bundle bundle = getArguments();
    contact = (DISContact) bundle.getSerializable(KEY);

Por supuesto, su objeto debe implementar Serializable

Al usar nuestro sitio, usted reconoce que ha leído y comprende nuestra Política de Cookies y Política de Privacidad.
Licensed under cc by-sa 3.0 with attribution required.