Iam new to android .I need to go back to the FragmentActivity from fragment page.
My work flow is:
MainActivity->ProfileActivity->ProfilePhotoEditFragment
I need to go back to
ProfilePhotoEditFragment -> ProfileActivity
manifest
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="16" />
ProfilePhotoEditFragment.java
public class ProfilePhotoEditFragment extends Fragment implements OnClickListener {
ViewUtils mViewUtils;
Bundle mSavedInstanceState;
private OnNavigateProfileListener mOnNavigateProfileListener;
private Button mCancelButton;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Context mContext = getActivity().getApplicationContext();
mViewUtils = new ViewUtils(mContext);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mSavedInstanceState = savedInstanceState;
View view = inflater.inflate(R.layout.fragment_edit_profile_pic, container, false);
mCancelButton = (Button) view.findViewById(R.id.cancel);
mCancelButton.setOnClickListener(this);
return view;
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onClick(View view) {
if (view.getId() == mCancelButton.getId()){
onBackPressed();
}
}
public void onBackPressed() {
// do something on back.
return;
}
}
remove current fragment ProfilePhotoEditFragment in onBackPressed()
if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
//( "stackzeo");
} else {
getSupportFragmentManager().popBackStack();
removeCurrentFragment();
//("stacknotzeo");
}
..
public void removeCurrentFragment() {
Fragment currentFrag = (Fragment) getFragmentManager()
.findFragmentById(R.id.content_frame);
if (currentFrag != null)
getFragmentManager().beginTransaction().remove(currentFrag);
getFragmentManager().beginTransaction().commit();
}
Call findFragmentById() on FragmentManager and determine which fragment is in your R.id.content_frame container.
Thank you All. this my working code
....
#Override
public void onClick(View view) {
if (view.getId() == mCancelButton.getId()){
getActivity().getSupportFragmentManager().popBackStack();
removeCurrentFragment();
}
}
public void removeCurrentFragment()
{
FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
Fragment currentFrag = getActivity().getSupportFragmentManager().findFragmentById(R.id.fragment_common_profile_layout);
String fragName = "NONE";
if (currentFrag!=null)
fragName = currentFrag.getClass().getSimpleName();
if (currentFrag != null)
transaction.remove(currentFrag);
transaction.commit();
}
getActivity().onBackPressed();
You should be able to call this code from every fragment.
Please check, if getActivity() returns null.
Hope this helps.
just write down
public void onBackPressed(){
super.onBackPressed();
}
Related
I know this has to be simple and I'm probably not seeing the solution.
Here is the brief description of what I have:
SignInActivity(AppCompatActivity) - handle the Firebase authentication, on success calls the method:
private void onAuthSuccess(FirebaseUser user) {
// Go to MainActivity
startActivity(new Intent(SignInActivity.this, MainActivity.class));
finish();
}
MainActivity(AppCompatActivity) - handle the menus for the application, this menu in particular are fragments with buttons. When a button is clicked I change the fragment that contains other buttons. Something like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager()
.beginTransaction()
.setCustomAnimations(R.anim.slide_in_up, R.anim.slide_out_left)
.replace(R.id.fragmentContent, MainMenuFragment.newInstance())
.commitNow();
}
getSupportFragmentManager().addOnBackStackChangedListener(new
FragmentManager.OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
int stackHeight = getSupportFragmentManager().getBackStackEntryCount();
getSupportActionBar().setHomeButtonEnabled(stackHeight > 0);
getSupportActionBar().setDisplayHomeAsUpEnabled(stackHeight > 0);
}
});
}
public void replaceFragments(Class fragmentClass, boolean isBack) {
Fragment fragment = null;
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
if (isBack) {
ft.setCustomAnimations(R.anim.slide_in_left, R.anim.slide_out_right);
} else {
ft.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left, R.anim.slide_in_left, R.anim.slide_out_right);
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
fragment = null;
e.printStackTrace();
}
if (fragment != null) {
ft.replace(R.id.fragmentContent, fragment);
ft.addToBackStack(fragmentClass.getName());
ft.commit();
}
}
MainMenuFragment(Fragment) - First set of options, several buttons on top of each other. Depending on the button clicked will call MainActivity.replaceFragment passing the next Fragment to go.
public class MainMenuFragment extends Fragment {
private static final String TAG = "MainMenuFragment";
public static MainMenuFragment newInstance() {
return new MainMenuFragment();
}
public MainMenuFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_main_menu, container, false);
final Button btnAssets = view.findViewById(R.id.btnAssets);
final Button btnAudit = view.findViewById(R.id.btnAudit);
btnAssets.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i(TAG, "BtnAssets_onClick");
((MainActivity)getActivity()).replaceFragments(AssetMenuFragment.class);
}
});
btnAudit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i(TAG, "BtnAudit_onClick");
((MainActivity)getActivity()).replaceFragments(AuditMenuFragment.class);
}
});
return view;
}
}
The AssetMenuFragment and the AuditMenuFragment are pretty much the same as the MainMenu, only the text for the buttons and some layout details changes.
When I'm using the app I first signIn, which leads me to the MainActivity, which loads the MainMenuFragment on onCreate. There I'm presented with two buttons, one to go to the AssetMenuFragment and the other to go to the AuditMenuFragment, they replace the fragment with their according layouts.
If I click the Asset button, once the fragment is replaced, because of:
getSupportActionBar().setHomeButtonEnabled(stackHeight > 0);
getSupportActionBar().setDisplayHomeAsUpEnabled(stackHeight > 0);
I'm presented with the back arrow to go back to MainMenuFragment. Everything works as expected.
Now the problem! If I'm in this AssetMenuFragment, with my beautiful back arrow showing on the ActionBar and decided to click the "Square" button on the device, which is probably run the onPause and onStop, and them click on the app again, which will run the onCreate and onStart again, my back arrow disappears, because now int stackHeight = getSupportFragmentManager().getBackStackEntryCount(); is zero.
How can I save my stack and restore it later so I can press back on the AssetMenuFragment and go back to MainMenuFragment.
It is a lot to read, but I'll appreciate the help, thanks!
In the end I knew it had to be something simple.
Both checks are correct.
getSupportActionBar().setHomeButtonEnabled(stackHeight > 0);
getSupportActionBar().setDisplayHomeAsUpEnabled(stackHeight > 0);
The problem was that I didn't check for them on onCreate, only on the getSupportFragmentManager().addOnBackStackChangedListener event.
Here is the MainActivity now:
private ActionBar actionBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager()
.beginTransaction()
.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left)
.replace(R.id.fragmentContent, MainMenuFragment.newInstance())
.commitNow();
}
actionBar = getSupportActionBar();
updateActionBarBackButton();
getSupportFragmentManager().addOnBackStackChangedListener(new
FragmentManager.OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
updateActionBarBackButton();
}
});
}
private void updateActionBarBackButton() {
int stackHeight = getSupportFragmentManager().getBackStackEntryCount();
getSupportActionBar().setHomeButtonEnabled(stackHeight > 0);
getSupportActionBar().setDisplayHomeAsUpEnabled(stackHeight > 0);
}
I have a MainActivity and a HomeTabs with three tabs (A B C), i set a refresh on tab C .
My structure is when i trigger onRefresh on tab C , i will switch to MainActivity
and load the data again to show the HomeTabs.
My problem is when i click back for finish(); , the layout will show tab C.
I try to finish the Fragment use like:
getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit();
or
((MainActivity)getActivity()).removeFragment(getActivity());
Both of them are no working , when i click back , i still can't finish the app immediately.
Some one can teach me what step i miss it , that would be appreciated.
My HomeTabs extends Fragment it use ViewPager and TabLayout add three tabs
MainActivity:
public class MainActivity extends AppCompatActivity {
private FrameLayout frameLayout;
private Toolbar toolBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
frameLayout = (FrameLayout) findViewById(R.id.frameLayout);
// Load the main Fragment
if (savedInstanceState == null) {
switchFragment(HomeTabs.newInstance());
}
//take the onRefresh dataļ¼send data to HomeTabs and open tab C
if (getIntent().hasExtra("refresh")) {
boolean isRefresh = getIntent().getExtras().getBoolean("refresh");
if (isRefresh) {
Bundle bundle = new Bundle();
bundle.putBoolean("refresh", isRefresh);
HomeTabs homeTabs = new HomeTabs();
homeTabs.setArguments(bundle);
switchFragment(homeTabs);
}
}
}
public void switchFragment(Fragment fragment) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.frameLayout, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
// I try to finsh my tab C , it's no working
public void removeFragment(Activity activity) {
activity.onBackPressed();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
new DialogHandler(this).quickDialog(
getResources().getString(R.string.quick),
getResources().getString(R.string.confirm),
getResources().getString(R.string.cancel),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// If i onRefrsh three times , i will finsh three times... here is my issue.
finish();
}
}, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
}
return super.onKeyDown(keyCode, event);
}
}
Here is my tab C Fragment refresh call back method:
public class MyLineChart extends Fragment implements SwipeRefreshLayout.OnRefreshListener{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_my_line_chart, container, false);
//.....................
return view;
}
#Override
public void onRefresh() {
refreshLayout.setRefreshing(false);
// Both of them are no working.
//((MainActivity)getActivity()).removeFragment(getActivity());
//getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit();
Intent intent = new Intent(getActivity(),MainActivity.class);
intent.putExtra("refresh", true);
startActivity(intent);
}
Finally my HomeTabs Fragment take the date and show tab C:
Bundle bundle = getArguments();
if (bundle != null) {
boolean isRefresh = bundle.getBoolean("refresh");
if (isRefresh) {
//tab C position is 2
tabLayout.getTabAt(2).select();
}
}
Try this solution to add below code when you are starting activity again on Refresh click:-
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
OR
Update your MainActivity.java
1) Add function in MainActivity
public void refreshFragment() {
Bundle bundle = new Bundle();
bundle.putBoolean("refresh", isRefresh);
HomeTabs homeTabs = new HomeTabs();
homeTabs.setArguments(bundle);
switchFragment(homeTabs);
}
Now Call that from Fragment Tab C just replacing startActivity(refresh) code:
MainActivity mainActivity = (MainActivity) getActivity();
mainActivity.refreshFragment();
you can add a listener in your fragment that can trigger a function in your parent activity
which means you need to add an interface in your fragmentC code
public class MyLineChart extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
private MyLineChartListener fragmentListener;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_my_line_chart, container, false);
//.....................
return view;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof MyLineChartListener) {
fragmentListener = (MyLineChartListener) context;
} else {
// throw an error
}
}
#Override
public void onRefresh() {
refreshLayout.setRefreshing(false);
// Both of them are no working.
//((MainActivity)getActivity()).removeFragment(getActivity());
//getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit();
fragmentListener.onSettingRefresh();
}
public interface MyLineChartListener {
void onSettingRefresh();
}
}
then you need to implement the listener in the MainActivity code as follows
public class MainActivity extends AppCompatActivity implements MyLineChart.MyLineChartListener {
private FrameLayout frameLayout;
private Toolbar toolBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
frameLayout = (FrameLayout) findViewById(R.id.frameLayout);
// Load the main Fragment
if (savedInstanceState == null) {
switchFragment(HomeTabs.newInstance());
}
}
public void switchFragment(Fragment fragment) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.frameLayout, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
// I try to finsh my tab C , it's no working
public void removeFragment(Activity activity) {
activity.onBackPressed();
}
// this function will be called when the fragment is refreshed
#Override
public void onSettingRefresh() {
Bundle bundle = new Bundle();
bundle.putBoolean("refresh", true);
HomeTabs homeTabs = new HomeTabs();
homeTabs.setArguments(bundle);
switchFragment(homeTabs);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
new DialogHandler(this).quickDialog(
getResources().getString(R.string.quick),
getResources().getString(R.string.confirm),
getResources().getString(R.string.cancel),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// If i onRefrsh three times , i will finsh three times... here is my issue.
finish();
}
}, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
}
return super.onKeyDown(keyCode, event);
}
}
The buttons don't work when I change into landscape mode and back to portrait. Anyways, here is my code:
public class fragmentone extends Fragment {
Button biological;
Button natural;
View myView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.firstlay, container, false);
biological = (Button) myView.findViewById(R.id.biological);
biological.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BiologicalHazards fragment = new BiologicalHazards();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
fragmentManager.beginTransaction().addToBackStack("hi")
.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out)
.replace(R.id.container1, fragment)
.commit();
}
});
natural = (Button) myView.findViewById(R.id.natural);
natural.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
NaturalHazards fragment = new NaturalHazards();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
fragmentManager.beginTransaction().addToBackStack("hi")
.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out)
.replace(R.id.container1, fragment)
.commit();
}
});
return myView;
}
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if(newConfig.orientation==Configuration.ORIENTATION_LANDSCAPE){
getActivity().setContentView(R.layout.firstlay);
}else{
getActivity().setContentView(R.layout.firstlay);
}
}
}
Does anyone know how to solve this? Any help is appreciated and thanks in advance.
you need to add setRetainInstance(true); //to your fragment onCreateView()
Also needn't be doing this getActivity().setContentView(R.layout.firstlay); in your onConfigurationChanged() method.
Hope this help :)
I think You to have re initilize when change orientation
try your modified code
private LayoutInflater inflater;
#Override
public View onCreateView(LayoutInflater inflater,
#Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myView = inflater.inflate(R.layout.firstlay, container, false);
reInitilize(myView);
return myView;
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
// TODO Auto-generated method stub
super.onConfigurationChanged(newConfig);
if(newConfig.orientation==Configuration.ORIENTATION_LANDSCAPE){
myView = inflater.inflate(R.layout.firstlay, null);
reInitilize(myView);
}else{
myView = inflater.inflate(R.layout.firstlay, null);
reInitilize(myView);
}
}
private void reInitilize(View myView) {
// TODO Auto-generated method stub
biological = (Button) myView.findViewById(R.id.biological);
biological.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BiologicalHazards fragment = new BiologicalHazards();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
fragmentManager.beginTransaction().addToBackStack("hi")
.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out)
.replace(R.id.container1, fragment)
.commit();
}
});
natural = (Button) myView.findViewById(R.id.natural);
natural.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
NaturalHazards fragment = new NaturalHazards();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
fragmentManager.beginTransaction().addToBackStack("hi")
.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out)
.replace(R.id.container1, fragment)
.commit();
}
});
}
You don't need to do handle orientation your self just to change your layout. Create 2 files with this same name R.layout.fistlay. One in res/layout, one in res/layout-land. Android will automatically pick the right one base on the orientation.
you could implement the method
#Override
protected void onSaveInstanceState(Bundle bundle){
// store some variable like boolean, ints, String to the bundle
bundle.putBoolean('currentFragment', isInFragmentA);
// call the default method
super.onSaveInstanceState(bundle);
}
After this, you could check if you are on a configuration change as following:
void onCreate(Bundle bundle){
if (bundle == null){
//start the activity as the use is opening the app as normal
} else {
// bundle is not null
//get back the variable you have store and act accordingly
// e.g do some FragmentTransition
}
}
Hope this help
Could you anyone advice me how to implement saveFragmentInstanceState() or some other methods to retrieving fragment instance when back button is pressed. I use own stack for fragment, viz code bellow:
public class stackA extends ActivityInTab {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i("StackA", "onCreate");
if(savedInstanceState == null){
navigateTo(new fragmentA());
}
}
}
Next there is implementation of ActivityInTab class. I think for this class must be implemented methods for saving and retrieving fragment state but still I can't find the way how to do this.
abstract class ActivityInTab extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_in_tab);
Log.i("ActivityInTab", "onCreate");
}
protected void navigateTo(Fragment newFragment) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction ft = manager.beginTransaction();
ft.replace(R.id.content, newFragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(null);
ft.commit();
}
#Override
public void onBackPressed() {
Log.i("ActivityInTab", "onBackPressed");
FragmentManager manager = getSupportFragmentManager();
if (manager.getBackStackEntryCount() > 1) {
super.onBackPressed();
} else {
// Otherwise, ask user if he wants to leave :)
//showExitDialog();
super.onBackPressed();
}
}
}
And finally, this is imlementation of Fragments:
public class fragmentA extends Fragment {
private LinearLayout ll;
private FragmentActivity fa;
private String textViewText;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.i("Fragment A", "onCreateView");
fa = super.getActivity();
ll = (LinearLayout) inflater.inflate(R.layout.fragmenta, container,
false);
Button next = (Button) ll.findViewById(R.id.button1);
Button randomBtn = (Button) ll.findViewById(R.id.random_button);
final TextView randomText = (TextView) ll
.findViewById(R.id.random_textview);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
((ActivityInTab) getActivity()).navigateTo(new
fragmentB());
}
});
randomBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
randomText.setText(String.valueOf(Math.random()));
textViewText = randomText.getText().toString();
}
});
if (savedInstanceState != null) {
randomText.setText(savedInstanceState.getString("TextView"));
}
return ll;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// setRetainInstance(true);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("TextView", textViewText);
}
}
I'm able to save instance state only for orientation changes using onSaveInstanceState(Bundle outState), but no for back button.
I would be very grateful for any advice, thanks.
In the onBackPressed Method you have access to the FragmentManager which can retrieve any fragment for you using the FragmentManager methods "findFragmentById" or "findFragmentByTag".
You can get direct access to any fragment whos state you want to save using either of those two methods depending on how you added the fragments.
I'm starting with fragments and I'm facing a problem. I wan't to restore my fragment after a screen rotation.
My app looks like this: on landscape I have a button on the left area, which updates the a label on the right area. If on portrait mode, I'm navigating to a new activity. However, I wan't to maintain the fragment state after rotating.
Code looks like this:
Left area fragment:
public class ListFragment extends Fragment implements OnClickListener {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_list, container, false);
Button button = (Button) view.findViewById(R.id.button1);
button.setOnClickListener(this);
return view;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
updateDetail();
break;
}
}
public void updateDetail() {
String newTime = String.valueOf(System.currentTimeMillis());
DetailFragment fragment = (DetailFragment) getFragmentManager()
.findFragmentById(R.id.detailFragment);
if (fragment != null && fragment.isInLayout()) {
fragment.setText(newTime);
} else {
Intent intent = new Intent(getActivity().getApplicationContext(),
DetailActivity.class);
intent.putExtra("value", newTime);
startActivity(intent);
}
}
}
Right area activity:
public class DetailActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
finish();
return;
}
if (savedInstanceState == null) {
setContentView(R.layout.activity_detail);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String s = extras.getString("value");
TextView view = (TextView) findViewById(R.id.detailsText);
view.setText(s);
}
}
}
}
Right area fragment:
public class DetailFragment extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater
.inflate(R.layout.fragment_detail, container, false);
return view;
}
public void setText(String item) {
TextView view = (TextView) getView().findViewById(R.id.detailsText);
view.setText(item);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
FragmentManager fm = getFragmentManager();
DetailFragment fragment = (DetailFragment)fm.findFragmentById(R.id.detailFragment);
if (fragment == null) {
fragment = new DetailFragment();
fragment.setTargetFragment(this, 0);
fm.beginTransaction().add(R.id.detailFragment, fragment).commit();
}
}
}
What can I possibly be doing wrong?
You have a few options you can use the Bundle in a couple of methods to save and restore the state of the fragments.
Or you can possibly use the setRetainInstance method:
onCreate(Bundle save)
{
super.onCreate(save);
setRetainInstance(true);
}
Keep in mind that the setRetainInstance method doesn't work for fragments in the backstack.
#Override
public void onConfigurationChanged(Configuration newConfig) {
int orientation = getResources().getConfiguration().orientation;
switch (orientation) {
case Configuration.ORIENTATION_LANDSCAPE:
getSupportFragmentManager().beginTransaction().replace(R.id.detailFragment, new DetailFragment()).commitAllowingStateLoss();
getSupportFragmentManager().beginTransaction().remove(new DetailFragment()).commitAllowingStateLoss();
break;
case Configuration.ORIENTATION_PORTRAIT:
getSupportFragmentManager().beginTransaction().replace(R.id.detailFragment, new DetailFragment()).commitAllowingStateLoss();
getSupportFragmentManager().beginTransaction().remove(new DetailFragment()).commitAllowingStateLoss();
break;
}
super.onConfigurationChanged(newConfig);
}
You can check on the onConfigurationChange and ensure that your fragment state is not lost by doing a commitAllowingStateLoss