There is a tabLayout and ViewPager. So I want to pass data from fragment1 to fragment2.
NOTE: fragment1 vs fragment2 lies in VIewPager. So I can't pass data follow normal ways.
FragmentTransaction fragmentTx=this.FragmentManager.BeginTransaction();
TracksByGenres fragTrack=new TracksByGenres();
fragTrack.AddData(items[e.Position]);
//get our item from listview
fragmentTx.Replace(Resource.Id.fragmentContainer,fragTrack);
fragmentTx.AddToBackStack(null);
fragmentTx.Commit();
Use sharedPreferences
SharedPreferences sharedpreferences;
public static final String MyPREFERENCES = "MyPrefs" ;
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
Save value
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("TAG_NAME", "value");
editor.commit();
Retrieve data from preference: In Second fragment
public static final String MyPREFERENCES = "MyPrefs" ;
SharedPreferences prefs = getSharedPreferences(MyPREFERENCES , MODE_PRIVATE);
String restoredText = prefs.getString("TAG_NAME", null);
This is an old question and all above answers are valid.This is 2019 and Android have changed a lot since Android Architecture Components
If you are using Android JetPack than you can add an Observer on a Live Data
in your Host Activity class and listen for changes in Fragment class
Create a Singleton repo to hold live data
/**
* Data Class Live Data
*/
class Repository private constructor() {
private var currentProgress: MutableLiveData<Float> = MutableLiveData()
fun getLiveProgress(): MutableLiveData<Float> {
return currentProgress
}
companion object {
private val mInstance: Repository =
Repository()
@Synchronized
fun getInstance(): Repository {
return mInstance
}
}
}
Set Live data anywhere from Activity or Fragment class class
viewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
override fun onPageScrollStateChanged(state: Int) {
}
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
headMotionScene.progress = positionOffset
Repository.getInstance().getLiveProgress().value = positionOffset
}
override fun onPageSelected(position: Int) {
}
})
Observe change in data from your Fragment/ Service class
Repository.getInstance().getLiveProgress().observe(this, Observer<Float> {
motionLayout.progress = it
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With