I have FragmentActivity with FrameLayout and I dynamically add Fragment1 to it. Then after the button click in the Fragment1 I replace it by the Fragment2 :
streetEdit.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
Log.i(TAG, "onTocuh");
FragmentTransaction trans = getFragmentManager().beginTransaction();
trans.replace(R.id.fragment_container, new StreetsFragment());
trans.addToBackStack(null);
trans.commit();
}});
Then I need I have list in Fragment2 and when user chooses one of the items, I need to close the Fragment2 and display the data in the Fragment1 . Analog to the onActivityResult for the Activities. I find the popBackStack() method using the best solution because of the simplicity :
street_list.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
GeoStreet choosed = adapter.getItem(position);
Intent intent = new Intent();
Bundle bundle = new Bundle();
bundle.putParcelable(Constants.CHOOSED_GEOSTREET, choosed);
intent.putExtras(bundle);
listener.passData(intent);
getFragmentManager().popBackStackImmediate();
}
});
I have interface IClickListener and I communicate with it between the Activity and Fragment. listener
is the object of the interface.
Then, in the Activity :
@Override
public void passData(Intent flag) {
if (flag != null)
{
if ( getSupportFragmentManager().findFragmentById(R.id.fragment_container) instanceof StreetsFragment)
{
GeoStreet street = flag.getExtras().getParcelable(Constants.CHOOSED_GEOSTREET);
Toast.makeText(getApplicationContext(), street.getName(), Toast.LENGTH_LONG).show();
Fragment frag = getSupportFragmentManager().findFragmentById(R.id.fragment_container);
Log.i(TAG, frag.getClass().toString());
setStreet(street.getName());
Bundle bundle = new Bundle();
bundle.putString(Constants.CHOOSED_GEOSTREET,street.getName());
if (getSupportFragmentManager().findFragmentById(R.id.fragment_container) instanceof ToStreetFragment)
{
Log.i(TAG , flag.toString());
ToStreetFragment fragment = (ToStreetFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_container);
fragment.setStreet(street.getName());
}
}
}
}
So, I can get the passed data from the Fragment2 and now I need to pass it to the Fragment1. I don't need to instantiate new Fragment1, but to use existing. I tried to use setters\getters in the Activity, and the get value in the Fragment1, but I've got nothing.
For sure, I can use removing \ adding method, or use SharedPreferences, but I think it can be simple solution. Thank you for yours suggestions.
0 comments:
Post a Comment