简体   繁体   中英

How to get value from another activity and bring back to previous fragment?

I have an Activity that have 3 fragment(FragmentA, FragmentB, FragmentC) like sliding tab. From FragmentB call another activity (lets call ActivityBB). After get item from Activity BB, How I can get value from ActivityBB and bring back to previous FragmentB ???

Well there are three ways that just comes in my mind. There may be more. But for now let me tell you those.

  1. On ActivityBB put the values that you want to save in SharedPreferences. And then restart your activity. Well yes this might only work if you have values that can be arranged in key-value pairs. And is also not the proper way to do things. But will get your job done.

To restart an activity use this code. and then get your values from SharedPreferences.

Intent intent = getIntent();
finish();
startActivity(intent);
  1. You can implement interfaces. This method is the best way to communicate between fragments. For more details check the google's documentation.

http://developer.android.com/training/basics/fragments/communicating.html

  1. You can use Bundles. For that check this link.

How to pass a value from one Fragment to another in Android?

You can try some like this.. Pass your value into intent.

This code in your ActivityBB

 Intent intent = new Intent(ActivityBB.this,ActivityBB.class);
            intent.putExtra("yourDataKey",yourData)
            startActivity(intent);

After that get your value into ActivityAA and load your Fragment with desired data

Intent intent = getIntent();
String yourValue = intent.getExtra("yourDataKey");

I solved this use intent and bundel with this flow :

  • MainActivity(FragmentA, FragmentB, FragmentC)
    This activty(eq : from FragmentB) pass data using intent to ActivityBB

  • ActivityBB at onClick ListItem in this activity, I pass data using bundle and call MainActivity (because I want to back to my previous fragment with item value from ActivityBB)

  • I make a condition from bundle at onCreate method at MainActivity to display currentItem(viewPager)

Actually its work, but I think this is not the proper way. I hope there is a solution with proper way from anyone to solve this.

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