I am using sherlock library. My problem is i am unable to change fragments on different button clicks.
Here is my code:
public class AmecmainActivity extends FragmentActivity {
private ImageButton legislativebutton;
private ImageButton About;
private ImageButton OutageReport;
private ImageButton ViewPageReportLeft;
private ImageView ViewPageReportRight;
private ImageButton actionnetwork;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.amecmain);
actionnetwork=(ImageButton)findViewById(R.id.Actionnetwork);
actionnetwork.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Bundle b = new Bundle();
b.putString("action", "actionnetwork");
Intent intent = new Intent(v.getContext(),
FragmentChangeActivity.class);
intent.putExtras(b);
startActivity(intent);
}
});
ViewPageReportLeft.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Bundle b = new Bundle();
b.putString("html", "htmlcontent");
Intent intent = new Intent(v.getContext(),
FragmentChangeActivity.class);
intent.putExtras(b);
startActivity(intent);
}
});
}
In this I'm using a common functionality
public class FragmentChangeActivity extends SlidingFragmentActivity {
private Fragment mContent;
public FragmentChangeActivity() {
super();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent in = getIntent();
Bundle b = in.getExtras();
String name= b.getString("action");
//Here i am getting the values through intent so that i can give that name
// set the fragment.
// set the Above View
if (savedInstanceState != null)
mContent = getSupportFragmentManager().getFragment(b, "action");
if (mContent==name)// Here i am setting fragments i dnot know to check the
// condition here mContent is fragment and i am giving
// string how to check the condition.
mContent = new Fragment1(); //here i am setting fragment
// set the Above View
setContentView(R.layout.content_frame);
getSupportFragmentManager().beginTransaction()
.replace(R.id.content_frame, mContent).commit();
// set the Behind View
setBehindContentView(R.layout.menu_frame);
getSupportFragmentManager().beginTransaction()
.replace(R.id.menu_frame, new ColorMenuFragment()).commit();
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
getSupportFragmentManager().putFragment(outState, "mContent", mContent);
}
public void switchContent(Fragment fragment) // Here is switchcontent method which
// will change the fragment content
{
mContent = fragment;
getSupportFragmentManager().beginTransaction()
.replace(R.id.content_frame, fragment).commit();
getSlidingMenu().showContent();
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.menuIcon:
toggle();
break;
case android.R.id.home:
getFragmentManager().executePendingTransactions();
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Related
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);
}
}
I actually have an aplication with multiple activitys (on for each icon of my toolbar), also I would like to have the possibility to show the last fragment of these activitys from the stack if the user already open it before.
As you can see in my BaseActivity class below (which I extend for all my activitys), I already add fragments to the stack.
This is my class :
public class BaseActivity extends AppCompatActivity {
private final String TAG = "BaseActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_base);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return false;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
public void setImageLoaderConfig(Context context) {
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheInMemory(true).cacheOnDisk(true)
.resetViewBeforeLoading(true)
.build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
.defaultDisplayImageOptions(defaultOptions)
.build();
ImageLoader.getInstance().init(config);
}
public void initToolBar() {
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.toolbar_layout);
Toolbar toolbar = (Toolbar) linearLayout.findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (toolbar != null) {
initToolbarOnClickListener();
}
}
private void initToolbarOnClickListener() {
(findViewById(R.id.toolbar_relativelayout_news)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showActivity(ArticlesActivity.class);
}
});
(findViewById(R.id.toolbar_relativelayout_toilettes)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showActivity(ToilettesActivity.class);
}
});
(findViewById(R.id.toolbar_relativelayout_practice)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showActivity(PratiquesActivity.class);
}
});
(findViewById(R.id.toolbar_relativelayout_diary)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showActivity(AgendaActivity.class);
}
});
(findViewById(R.id.toolbar_relativelayout_forum)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showActivity(ForumActivity.class);
}
});
}
public void updateToolbarIcons(Integer position) {
ImageView imageViewIcon;
Integer[] activeDrawableIds = {R.drawable.menu_actu_hover_320, R.drawable.menu_toilette_hover_320,
R.drawable.menu_pratiques_hover_320, R.drawable.menu_agenda_hover_320, R.drawable.menu_forum_hover_320};
Integer[] inactiveDrawableIds = {R.drawable.menu_actu_160, R.drawable.menu_toilette_320,
R.drawable.menu_pratiques_320, R.drawable.menu_agenda_320, R.drawable.menu_forum_320};
Integer[] imageviewIds = {R.id.toolbar_imageview_news, R.id.toolbar_imageview_bathroom,
R.id.toolbar_imageview_practice, R.id.toolbar_imageview_diary, R.id.toolbar_imageview_forum};
for (int i = 0; i < imageviewIds.length; i++) {
Log.d(TAG, i + " " + imageviewIds[i]);
imageViewIcon = (ImageView) findViewById(imageviewIds[i]);
if (i == position) {
imageViewIcon.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), activeDrawableIds[i]));
} else {
imageViewIcon.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), inactiveDrawableIds[i]));
}
}
if (AfamiciApp.isConnected()) {
ImageView imageViewUser = (ImageView) findViewById(R.id.toolbar_imageview_user);
imageViewUser.setVisibility(View.VISIBLE);
}
}
public void showActivity(Class activityClass) {
Intent intent = new Intent(this, activityClass);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
public void initIsConnected() {
if (AfamiciApp.getMail() != null && AfamiciApp.getPassword() != null) {
AfamiciApp.setIsConnected(true);
}
}
public void showConnexionFragment(Integer layoutId, Integer id) {
Bundle args = new Bundle();
args.putInt("id", id);
args.putInt("containerId", layoutId);
ConnexionFragment connexionFragment = new ConnexionFragment();
connexionFragment.setArguments(args);
getSupportFragmentManager()
.beginTransaction()
.replace(layoutId, connexionFragment, null)
.addToBackStack(null)
.commit();
}
public void showCreationCommentaireFragment(Integer layoutId, Integer id, Boolean isFromConnection) {
if (isFromConnection) {
getSupportFragmentManager().popBackStack();
}
Bundle args = new Bundle();
args.putInt("id", id);
CommentaireFragment commentaireFragment = new CommentaireFragment();
commentaireFragment.setArguments(args);
getSupportFragmentManager()
.beginTransaction()
.replace(layoutId, commentaireFragment, null)
.addToBackStack(null)
.commit();
}
public void showCreationCompteFragment(Integer layoutId, Integer id) {
Bundle args = new Bundle();
args.putInt("id", id);
CreationCompteFragment creationCompteFragment = new CreationCompteFragment();
creationCompteFragment.setArguments(args);
getSupportFragmentManager()
.beginTransaction()
.replace(layoutId, creationCompteFragment, null)
.addToBackStack(null)
.commit();
}
}
Thanks in advance for your replys :)
You can get current fragment(last one added) in the FrameLayout using:
Fragment fragment = getSupportFragmentManager().findFragmentById(layoutId); //layoutId is id of FrameLayout
My activity consists of many fragments.FeedFragment consists of textviews which when i click opens a new actvity named FeedAnalysis.FeedAnalysis has close,next and previous textview on which onClick event is there.I have problem regarding close textview action.I want when i click on close textview it returns to the FeedFragment.But when i click on close textview it opens a new FeedFragment on top of it.As a result Sliding menu in my fragment doesn't appear.Also when i use back button of mobile, FeedAnalysis activity again appears.I want that my activity is destroyed once i click on close textview and my fragment to be displayed with sliding menu as it was previously.
I am using this code for close button
tv1 = (TextView) findViewById(R.id.textView21);
tv1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment newFragment = new FeedFragment();
fragmentTransaction.replace(android.R.id.content, newFragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
Here is my complete code for fragment and activity
FeedFragment
public class FeedFragment extends Fragment {
ActionBar actionBar;
private FragmentActivity myContext;
private ViewPager viewPager;
public FeedFragment() {
}
#Override
public void onAttach(Activity activity) {
myContext = (FragmentActivity) activity;
super.onAttach(activity);
}
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.news, container, false);
actionBar = getActivity().getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
TextView tv = (TextView) rootView.findViewById(R.id.textView11);
tv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent();
i.setClass(myContext, FeedAnalysis.class);
startActivity(i);
}
});
TextView tv1 = (TextView) rootView.findViewById(R.id.textView13);
tv1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent();
i.setClass(myContext, FeedAnalysis2.class);
startActivity(i);
}
});
TextView tv2 = (TextView) rootView.findViewById(R.id.textView43);
tv2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent();
i.setClass(myContext, FeedAnalysis3.class);
startActivity(i);
}
});
return rootView;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.action_search2:
Intent i = new Intent();
i.setClass(myContext, FeedSelect.class);
startActivity(i);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
FeedAnalysis
public class FeedAnalysis extends FragmentActivity {
TextView tv1, tv2, tv3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.newsdetails);
Configuration config = getResources().getConfiguration();
FragmentManager fragmentManager = getFragmentManager();
final FragmentTransaction fragmentTransaction =
fragmentManager.beginTransaction();
tv1 = (TextView) findViewById(R.id.textView21);
tv1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment newFragment = new FeedFragment();
fragmentTransaction.replace(android.R.id.content, newFragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
tv2 = (TextView) findViewById(R.id.textView22);
tv2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent();
i.setClass(getApplicationContext(), FeedAnalysis2.class);
startActivity(i);
}
});
tv3 = (TextView) findViewById(R.id.textView24);
tv3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent();
i.setClass(getApplicationContext(), FeedAnalysis3.class);
startActivity(i);
}
});
}
}
If you do finish() on Activity2, it will close Activity2 and all fragments that spawned from Activity2, and therefore it will return to Activity1 (or the fragments that spawned from Activity1).
(The names i used are just as an example)
That should solve your problem.
you should use finish(); method instead of startActivity(i);
I am using Action Bar Sherlock fragments for my application. I need to go to fragment from activity. But sliding menu is not working when I goes to fragment by using this code.
Activity Code
Intent notificationIntent = new Intent(context,FragmentOpenActivity.class);
FragmentOpenActvity is like
public class FragmentOpenActivity extends SherlockFragmentActivity {
private Bundle i_fragment;
private String messages = null;
private String coupons = null;
private String yo = null;
private String invitation = null;
private String loyalty = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
if (savedInstanceState == null) {
// getSupportFragmentManager().beginTransaction()
// .add(android.R.id.content, new MessagesFragment()).commit();
i_fragment = getIntent().getExtras();
if (i_fragment == null) {
getSupportFragmentManager().beginTransaction()
.add(android.R.id.content, new ProfileEditorFragment())
.commit();
} else {
messages = i_fragment.getString("Message");
coupons = i_fragment.getString("Coupon");
}
if (messages != null && messages.equalsIgnoreCase("Message")) {
getSupportFragmentManager().beginTransaction()
.add(android.R.id.content, new MessagesFragment())
.commit();
} else if (coupons != null && coupons.equalsIgnoreCase("Coupon")) {
getSupportFragmentManager().beginTransaction()
.add(android.R.id.content, new CouponsFragment())
.commit();
} else {
getSupportFragmentManager().beginTransaction()
.add(android.R.id.content, new ProfileEditorFragment())
.commit();
}
}
}
/**
* #return Displaying Action Bar Button with Image
*/
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
/**
* #return Click Events for Action Bar Buttons
*/
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
startActivity(new Intent(this, FragmentChangeActivity.class));
break;
}
return true;
}
/**
* #return Handling Back button
*/
public void onBackPressed() {
startActivity(new Intent(this, FragmentChangeActivity.class));
finish();
}
}
Please refer the following code for fragment
public class CouponsFragment extends SherlockFragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
getSherlockActivity().getSupportActionBar().setDisplayOptions(
ActionBar.DISPLAY_SHOW_CUSTOM);
getSherlockActivity().getSupportActionBar().setDisplayHomeAsUpEnabled(
true);
return inflater.inflate(R.layout.listview_refreshable, null);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
public void onStart() {
super.onStart();
}
}
Normally sliding menu works perfectly but when i came from FragmentOpenActivity it is not responding. Please try to find me a solution
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