Jak przenieść niektóre dane do innego fragmentu?


194

Jak przenieść niektóre dane do innego Fragmentpodobnie to było zrobione z extrasza intents?


Próbuję odpowiedzieć na to pytanie @ tutaj . Mam nadzieję, że to zadziała.
— ozhanli

Odpowiedzi:


482

Użyj a Bundle. Oto przykład:

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

Pakiet wprowadził metody dla wielu typów danych. Zobacz to

Następnie Fragmentpobierz dane (np. onCreate()Metodą) za pomocą:

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

1
Cześć, dziękuję za odpowiedź, ale czy musimy zaimplementować coś takiego jak Serializable lub Parcelable?
— Ankit Srivastava

Nie, nie musisz implementować żadnych klas.
— Gen

2
Może chcesz dodać czek, aby zobaczyć ten pakiet! = Null, zanim spróbujesz coś z niego wyciągnąć?
— Niels

A jeśli masz istniejący fragment w pamięci?
— powder366

to kod nie działa, nie przekierowuje aktywności do fragmentowania z danymi
— Venkatesh

44

Aby jeszcze bardziej rozszerzyć poprzednią odpowiedź, jak mawiał Ankit, w przypadku złożonych obiektów należy zaimplementować Serializable. Na przykład dla prostego obiektu:

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

W tobie 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();

w ToFragment:

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

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

Jesteś najlepszy. Dzięki
— hash

1
@Sameera Zazwyczaj po prostu umieszczam ciąg znaków w mojej klasie fragmentów, tzn. Jeśli mam klasę MyFragmentIMGoingTo.java, to moja TAG_TO_FRAGMENT = "MyFragmentIMGoingTo";
— mike.tihonchik,

Lepsze wykorzystanie Parcelable, ponieważ Google polecił go jako bardziej zoptymalizowaną technikę serializacji dla systemu operacyjnego Android.
— Klejnot

16

getArguments () zwraca null, ponieważ „Nic nie dostaje”

Wypróbuj ten kod, aby poradzić sobie z tą sytuacją

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

Cześć, dziękuję za odpowiedź, ale czy musimy zaimplementować coś takiego jak Serializable lub Parcelable?
— Ankit Srivastava

jesteś pewien? ponieważ musiałem zaimplementować Serializable / Parcelable, kiedy przekazywałem złożone dane między fragmentem a działaniem przy użyciu zamiaru ......
— Ankit Srivastava

próbowałem tylko z prostymi wartościami. Przykro nam
— mam

1
To powinien być komentarz, a nie odpowiedź !!
— Klejnot

14

Kompletny kod przekazywania danych przy użyciu fragmentu fragmentu

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();

W niestandardowej klasie fragmentu

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

skąd wziąć viewID?
— Hoo

@Hoo: proszę podać swoje pytanie, co chcesz zadać
— Anand Savjani,


5

Aby rozszerzyć poprzednie odpowiedzi - może komuś pomóc. Jeśli getArguments()zwracasz null, umieść to w onCreate()metodzie, a nie w konstruktorze swojego fragmentu:

@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
Wyjaśnij swoją odpowiedź? kod bez żadnego wyjaśnienia niewiele pomoże
— Coder

Napisałem kod w przepływie, aby można go było zrozumieć ..... Przekazywanie danych z głównej działalności do FragClass1 za pomocą pakietu.
— Sumedh Ulhe,

1

Z klasy aktywności:

Wyślij dane przy użyciu argumentów pakietu do fragmentu i załaduj fragment

   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();

Z klasy myFragment:

Pobierz argumenty z pakietu i ustaw je na 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);

Przeczytaj jeszcze raz pytanie, Chodzi o fragment po fragmencie
— Amin Pinjari,

1

Oto jak korzystasz z pakietu:

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

pobierz wartość z pakietu:

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

0

Twój fragment wejściowy

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();

        }
    };



}

twój fragment widoku

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

Jeśli używasz wykresu do nawigacji między fragmentami, możesz to zrobić: Z fragmentu A:

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

Aby podzielić fragment B:

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

Oczywiście twój obiekt musi implementować Serializable

Korzystając z naszej strony potwierdzasz, że przeczytałeś(-aś) i rozumiesz nasze zasady używania plików cookie i zasady ochrony prywatności.
Licensed under cc by-sa 3.0 with attribution required.