简体   繁体   中英

Passing value between fragment?

I want to passing value from fragment A to fragment B.

The logic is: in fragment A. value= 10, and fragment B, receive the value from fragment A. so the fragment B have a same value=10

Now, in fragment Ai have a button for increment value. So the value is 10 And i wanna fragment B have a same value

How to receive the value from fragment A?

I can't receive the value from fragment A for the second time because method onStart() just can call once.

This the source code: Fragment A:

/*
     * Passing value from Lirik to Notangka
     * code from: developer.android.com
     */
    Notangka notangka = (Notangka) getFragmentManager().findFragmentById(R.id.fragmentnotangka);

    if (notangka != null){
        Log.v("Lirik.gettingdata", "menjalankan notangka != null");

    } else {
        Log.v("Lirik.gettingdata", "menjalankan selain notangka != null");
        Notangka newFragment = new Notangka();
        Bundle args = new Bundle();
        Log.v("Lirik.notangka() - Not angka", "cek kondisi nolagu "+nolagu+" \nbuku "+buku);
        args.putString("nolagu", nolagu);
        args.putString("buku", buku);
        newFragment.setArguments(args);
        FragmentTransaction transaction = getFragmentManager().beginTransaction();

        transaction.replace(R.id.fragmentnotangka, newFragment);
        transaction.addToBackStack(null);
        transaction.commit();

    }
    //=====================================END=FROM=PASSING=VALUE============================================

and now the fragment B

@Override
public void onStart() {
    super.onStart();

    Bundle args = getArguments();
    if (args != null){
        buku = args.getString("buku");
        nolagu = args.getString("nolagu");
        Log.v("Notangka.onStart()","value buku "+buku+" value nolagu "+nolagu);
    } else {
        Log.v("Notangka.datafromLirik.onStart()", "value buku :"+buku+" value nolagu "+nolagu);
    }
}

please help me

You should access extras in OnCreate method.

Here is the small example

@Override
public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            boku = getArguments().getString("buku");
            nolagu = getArguments().getString("nolagu");
            Log.v("Notangka.onCreate()","value buku "+buku+" value nolagu "+nolagu);
        }else
        {
            Log.v("Notangka.onCreate()","No Values are available");

        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM