Run code in ActionBar Tab Fragment when tab is removed - android

I've got Fragment ActionBar Tabs with an TabListener attached to every tab. In my main activity I got a delete tab button as follows:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()
case R.id.closeTab:
closeTab();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void closeTab() {
if(getActionBar().getTabCount() > 1) {
Tab tab = getActionBar().getSelectedTab();
getActionBar().removeTab(tab);
}
}
What I'm trying to accomplish is to run some code in my tab-fragment before it gets removed. I could place this in the fragments onDestroyView() or onDestroy() but I only whant to run this code when I press my delete tab button.
I have checked the documentation for the TabListener but it seems like TabListener only listens to selectionchanges.
My TabListener:
public TabListener(Activity a, String t, Class<T> c) {
activity = a;
tag = t;
myClass = c;
}
/* The following are each of the ActionBar.TabListener callbacks */
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// Check if the fragment is already initialized
if (fragment == null) {
// If not, instantiate and add it to the activity
fragment = Fragment.instantiate(activity, myClass.getName());
ft.add(android.R.id.content, fragment, tag);
} else {
// If it exists, simply attach it in order to show it
ft.attach(fragment);
}
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
if (fragment != null) {
// Detach the fragment, because another one is being attached
ft.detach(fragment);
}
}
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
To clarify my question: How can I run code in my Fragment before the tab is removed?

Okey, I figured it out after reading this post: link.
In my fragment I put setHasOptionMenu(true)
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
}
And then I could just add onOptionsItemSelected in my fragment.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.closeTab:
closeTab();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void closeTab() {
ActionBar actionBar = getActivity().getActionBar();
if(actionBar.getTabCount() > 1) {
Tab tab = actionBar.getSelectedTab();
actionBar.removeTab(tab);
Log.d(TAG, "CLOSED TAB");
}
}

Related

How to add back button on action bar with more tabs

know anyone how can I add one back button on my action bar? I want to add the back button befor INFO tab. I've try some method but no one of them don't work for me. Well let's start with started.
In this image in left part it's what I need to do as actionbar and in the right part it's how looks my project right now.
I've try to put that code for add the back button but it don't works:
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setHomeButtonEnabled(true);
Here it's my Activity:
public class TrailActivity extends FragmentActivity implements ActionBar.TabListener {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
Intent intent;
Trail trail;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
intent = getIntent();
setContentView(R.layout.trail_fracment_main);
trail = intent.getParcelableExtra("trail");
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setHomeButtonEnabled(true);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
actionBar.addTab(actionBar.newTab().setText(mSectionsPagerAdapter.getPageTitle(i)).setTabListener(this));
}
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
if (position == 0) {
InfoFragments infoFragments = new InfoFragments();
infoFragments.setTrail(trail);
Fragment fragment = infoFragments;
return fragment;
} else if (position == 1) {
return new MapFragments();
} else {
return new WondersFragments();
}
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
Some one told me to try to implement OnBackStackChangedListener and after that he want to put in my code and that:
#Override
public void onCreate(Bundle savedInstanceState) {
//Listen for changes in the back stack
getSupportFragmentManager().addOnBackStackChangedListener(this);
//Handle when activity is recreated like on orientation Change
shouldDisplayHomeUp();
}
#Override
public void onBackStackChanged() {
shouldDisplayHomeUp();
}
public void shouldDisplayHomeUp(){
//Enable Up button only if there are entries in the back stack
boolean canback = getSupportFragmentManager().getBackStackEntryCount()>0;
getSupportActionBar().setDisplayHomeAsUpEnabled(canback);
}
#Override
public boolean onSupportNavigateUp() {
//This method is called when the up button is pressed. Just the pop back stack.
getSupportFragmentManager().popBackStack();
return true;
}
Also I've try to add and that override method, but again... nothing happen :(
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// app icon in action bar clicked; goto parent activity.
this.finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
I've try and that... but again... I've don't obtain any result :(.
So please guys, if anyone know how can I solve that problem, please show me.. I really need to do that and how much fast is possible.

How to make an Android refresh button that refreshes the fragment in a drawer?

I am trying to refresh the fragment depending on what drawer the user is on...
This was my attempt which does not do anything but does not give me an error.
Here is my code
public void fragmentRefresh() {
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragmentManager.findFragmentByTag("TagForRefresh"))
.commit();
}
Here is the drawer fragment code:
/**
* Diplaying fragment view for selected nav drawer list item
*/
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new HomeFragment();
break;
case 1:
fragment = new BrowseFragment();
break;
case 2:
fragment = new InviteFragment();
break;
case 3:
fragment = new ProfileFragment();
break;
case 4:
fragment = new SettingsFragment();
break;
case 5:
callConfirmLogout();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment, "TagForRefresh").commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
Implemented in a tab swiper fragment class:
public class ViewVotesActivity extends FragmentActivity implements ActionBar.TabListener{
//Tab options
private ViewPager viewPager;
private TabSwipeAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private String[] tabs = { "Created", "Up", "Down"};
//for custom menu to add progress bar to refresh
private MenuItem menuItem;
//Search view action bar
private SearchView search_action_bar;
//getApplicationContext().getString(R.string.created),getApplicationContext().getString(R.string.upvote), getApplicationContext().getString(R.string.downvote)
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_votes);
// Initializing tab
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabSwipeAdapter(getSupportFragmentManager(), new UserCreatedFragment(), new UserUpVotesFragment(),new UserDownVotesFragment());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
/**
* on swiping the viewpager make respective tab selected
* */
/**
* on swiping the viewpager make respective tab selected
* */
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// on tab selected
// show respected fragment view
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.home, menu);
setupActions(menu);
callSearchActionBar(menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar actions click
switch (item.getItemId()) {
case R.id.action_refresh:
menuItem = item;
menuItem.setActionView(R.layout.refresh_progress_bar);
//menuItem.expandActionView();
fragmentRefresh();
TestTask task = new TestTask();
task.execute("test");
return true;
case R.id.action_discover:
addNewItem();
return true;
case R.id.action_search:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void addNewItem() {
// user redirect to register followup
Intent createItemIntent = new Intent(ViewVotesActivity.this, CreateItemActivity.class);
// Closing all the Activities
createItemIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
createItemIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
startActivity(createItemIntent);
}
public void fragmentRefresh() {
// // Insert the fragment by replacing any existing fragment
// FragmentManager fragmentManager = getFragmentManager();
//
// fragmentManager.beginTransaction()
// .replace(R.id.frame_container, fragmentManager.findFragmentByTag("TagForRefresh"))
// .commit();
}
private class TestTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
// Simulate something long running
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
menuItem.collapseActionView();
menuItem.setActionView(null);
}
};
public void setupActions(Menu menu) {
MenuItem refreshItem = menu.findItem(R.id.action_refresh);
MenuItem discoverItem = menu.findItem(R.id.action_discover);
if (isAlwaysExpanded()) {
} else {
refreshItem.setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_IF_ROOM
| MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
discoverItem.setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_IF_ROOM
| MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
}
}
public void callSearchActionBar(Menu menu) {
//find the menu item and set search view at the same time
MenuItem searchItem = menu.findItem(R.id.action_search);
search_action_bar
= (SearchView) searchItem.getActionView();
if (isAlwaysExpanded()) {
search_action_bar.setIconifiedByDefault(false);
} else {
searchItem.setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_IF_ROOM
| MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
}
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
if (searchManager != null) {
List<SearchableInfo> searchables = searchManager.getSearchablesInGlobalSearch();
SearchableInfo info = searchManager.getSearchableInfo(getComponentName());
for (SearchableInfo inf : searchables) {
if (inf.getSuggestAuthority() != null
&& inf.getSuggestAuthority().startsWith("applications")) {
info = inf;
}
}
search_action_bar.setSearchableInfo(info);
}
search_action_bar.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
public boolean onQueryTextChange(String newText) {
Log.e("Query = ", newText);
return false;
}
public boolean onQueryTextSubmit(String query) {
Log.e("Submit", "Submited " + query);
// user redirect to register followup
Intent searchIntent = new Intent(ViewVotesActivity.this, SearchActivity.class);
searchIntent.putExtra("search", query);
// Closing all the Activities
searchIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
searchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
startActivity(searchIntent);
return false;
}
public boolean onClose() {
Log.e("query close", "query closingggg");
return false;
}
});
}
protected boolean isAlwaysExpanded() {
return false;
}
}
UPDATE:
It looks like you're trying to tell an Activity that it's time to change the content fragment depending upon a selection in a Navigation Drawer.
This problem has two parts.
You need to provide a mechanism to communicate from your Drawer to your Activity, which, will, in turn, proceed to perform the necessary actions.
Your Fragments must either be Detached, Destroyed, Recreated and Reattached (inneficient, why?) or simply implement a mechanism that tells them: Hey, it's time to Refresh your content.
I don't see any reason why you need to completely destroy the Fragment's view if you only need to reset its data. Seems like a design flaw.
Replacing a Fragment should not mean you want to completely destroy it, since the user can simply go back or press the recently removed fragment. It would be inefficient to recreate it again.
Like I mentioned in the comments, more code is needed to see what your current approach is.
Normally a simple Interface (like the one I described below) should suffice. Your activity can receive the "clicks" in the Drawer and decide which fragment to replace (if needed).
Please be a lot more specific and provide more code.
Old Response:
Warning: if you're trying to replace the current fragment, make sure you're not getting the wrong FragmentManager. You do getFragmentManager() but I'm sure you're using the support library and therefore need to do getSupportFragmentManager();.
You've failed to mention what version you're targeting so it's hard to know.
On the other hand,
If what you want to do is tell the current visible fragment to refresh… you should use a more common approach to object-to-object communication.
You're over-complicating things.
(warning: pseudo code)
Create an interface like:
public interface Refreshable{
void onShouldRefresh();
}
Have a DrawerController capable of storing observers/listeners…
public class DrawerController {
private List<Refreshable> mListeners = new ArrayList<Refreshable>();
public void addRefreshListener(E listener) {
if (listener != null && !mListeners.contains(listener)) {
mListeners.add(listener);
}
}
public void removeRefreshListener(E listener) {
if (listener != null) {
mListeners.remove(listener);
}
}
}
Make your fragments implement it (and subscribe to the event when they are visible)
public class HomeFragment extends Fragment implements Refreshable {
// your fragment code
public void onShouldRefresh(){
// do the refresh
}
#Override
public void onResume() {
super.onResume();
yourDrawerController.addRefreshListener(this);
}
#Override
public void onPause() {
super.onPause();
yourDrawerController.removeRefreshListener(this);
}
}
Now make a method that will tell the interested parties (in this case your "Refreshable" objects) that it's time to refresh, add this to your DrawerController…
public void refresh(){
for (Refreshable listener : mListeners) {
if (listener != null) {
listener.onShouldRefresh();
}
}
}
Finally, in your code, call refresh() and have a beer.
Did I miss your point? it's not 100% clear to me.

Are tabs and Fragment menus incompatible in Android?

TLDR: Adding menu items for a fragment causes onTabSelected to be called infinitely.
I am working on an app for Android 4.0+ and have run into a problem. I am currently using an ActionBar with tabs, which works well. When I click a tab, the method onTabSelected(Tab, FragmentTransaction) is called once, and I switch the fragments that are shown on screen. Here is the method:
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
onTabSelected(tab, ft);
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
FragmentManager fragmentManager = getFragmentManager();
switch(tab.getPosition()) {
case 0 :
fragmentManager.beginTransaction()
.replace(R.id.buttons_box, ButtonsFragment.newInstance(0))
.commit();
fragmentManager.beginTransaction()
.replace(R.id.container, ControlsFragment.newInstance(0))
.commit();
break;
case 1 :
...
case 2 :
...
}
}
The problem arises when I want to add menu items for the fragment. In ControlsFragment, I add the following methods:
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
{
inflater.inflate(R.menu.controls, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch(item.getItemId())
{
case R.id.control_1 :
Toast.makeText(getActivity(), "Clicked Control 1", Toast.LENGTH_SHORT).show();
return true;
default :
return super.onOptionsItemSelected(item);
}
}
And added this line in onCreate(Bundle):
setHasOptionsMenu(true);
Only now, when the app is run, the first tab is selected by default, and the method onTabSelected in my Activity is called over and over again. Why does this occur? Are tabs and fragment menu items incompatible?
EDIT
I tried removing the call to onTabSelected from onTabReselected, but this did not fix the problem.
This was causing all sorts of issues, so I found a simple work-around. This simple hack fixes the strange issue.
Create a variable:
private Tab currentTab;
Add the following lines at the top of onTabSelected:
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
if (currentTab == null)
currentTab = tab;
else if (currentTab == tab)
return;
else
currentTab = tab;
//your code here
}

Fragment is re created when ActionbarSherlock tab is selected

I have a Fragment Activity which holds three fragments.
public class MainActivity extends SherlockFragmentActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBar bar = getSupportActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.Tab tab1 = bar.newTab();
ActionBar.Tab tab2 = bar.newTab();
ActionBar.Tab tab3 = bar.newTab();
tab1.setText("");
tab1.setIcon(R.drawable.abs__ic_menu_share_holo_dark);
tab2.setText("");
tab2.setIcon(R.drawable.abs__ic_voice_search);
tab3.setText("");
tab3.setIcon(R.drawable.abs__ic_cab_done_holo_dark);
if (savedInstanceState == null) {
tab1.setTabListener(new MyTabListener());
tab2.setTabListener(new MyTabListener());
tab3.setTabListener(new MyTabListener());
bar.addTab(tab1);
bar.addTab(tab2);
bar.addTab(tab3);
}
}
private class MyTabListener implements ActionBar.TabListener {
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
switch (tab.getPosition()) {
case 0:
FeedsActivity frag = new FeedsActivity();
ft.replace(android.R.id.content, frag);
return;
case 1:
ProfileActivity frag2 = new ProfileActivity();
ft.replace(android.R.id.content, frag2);
return;
case 2:
MyMemoirsActivity frag3 = new MyMemoirsActivity();
ft.replace(android.R.id.content, frag3);
return;
}
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
}
}
And here is first Fragment,
public class FeedsActivity extends SherlockFragment {
public static String[] MainCategory;
public static String[] MainCategoryId;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup group,
Bundle saved) {
setRetainInstance(true);
return inflater.inflate(R.layout.activity_feeds, group, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
new GetMainCategory(getActivity()).execute();
}
}
When I select second tab and then select first tab the async task in first fragment is called again.How can I retain state of first fragment so that its view is created once? I have used setRetainInstance(true) but didnt work.
I solved this issue by using show and hide instead of attach and detach.
private class MyTabListener implements ActionBar.TabListener {
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
switch (tab.getPosition()) {
case 0:
if (frag1 == null) {
// If not, instantiate and add it to the activity
frag1 = Fragment.instantiate(getApplicationContext(),
FeedsActivity.class.getName());
ft.add(android.R.id.content, frag1, "Feeds");
} else {
// If it exists, simply attach it in order to show it
ft.show(frag1);
}
return;
case 1:
if (frag2 == null) {
// If not, instantiate and add it to the activity
frag2 = Fragment.instantiate(getApplicationContext(),
ProfileActivity.class.getName());
ft.add(android.R.id.content, frag2, "Profile");
} else {
// If it exists, simply attach it in order to show it
ft.show(frag2);
}
return;
case 2:
if (frag3 == null) {
// If not, instantiate and add it to the activity
frag3 = Fragment.instantiate(getApplicationContext(),
History.class.getName());
ft.add(android.R.id.content, frag3, "History");
} else {
// If it exists, simply attach it in order to show it
ft.show(frag3);
}
return;
}
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
if (frag1 != null) {
// Detach the fragment, because another one is being attached
switch (tab.getPosition()) {
case 0:
ft.hide(frag1);
return;
case 1:
ft.hide(frag2);
return;
case 2:
ft.hide(frag3);
return;
}
}
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
}
The proper way to use TabListener is this :
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// Check if the fragment is already initialized
if (mFragment == null) {
// If not, instantiate and add it to the activity
mFragment = Fragment.instantiate(mActivity, mClass.getName());
ft.add(android.R.id.content, mFragment, mTag);
} else {
// If it exists, simply attach it in order to show it
ft.attach(mFragment);
}
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
if (mFragment != null) {
// Detach the fragment, because another one is being attached
ft.detach(mFragment);
}
}
#override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// User selected the already selected tab. Usually do nothing.
}
Basically you need to check if that's the first time when your Fragment is being initialised. If not, you should add it to your screen and when the user unselect a tab you should detach the current visible fragment and add the new one. That's the way it should work. You don't need to create a new instance of Fragment everytime user click the tab.

Orientation change with multiple fragments and different layouts

In landscape, I have an activity with previewFragment loaded into the R.id.fragment_container_child (on the left third of the screen) and selectionFragment loaded into R.id.fragment_container_parent (right two thirds of the screen). Selecting the second tab changes selectionFragment to contactFragment but previewFragment remains the same. This all works fine.Upon an orientation change, the layout is changed slightly via xml, where R.id.fragment_child now occupies the bottom third, instead of the left third. The problem arises when I change the orientation. My action bar and fragments disappear, although the layout is confirmed changing.I have not defined android:configChanges="orientation" in the Manifest file. Below is the code to my activity:
public class MainActivity extends Activity implements ActionBar.TabListener {
static SelectionFragment selectionFragment;
static ContactFragment contactFragment;
public static PreviewFragment previewFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (findViewById(R.id.fragment_container_child) != null) {
if (savedInstanceState != null) {
return;
}
previewFragment = new PreviewFragment();
selectionFragment = new SelectionFragment();
FragmentTransaction transaction = getFragmentManager()
.beginTransaction();
transaction.add(R.id.fragment_container_child, previewFragment,
"PREVIEW");
transaction.add(R.id.fragment_container_parent, selectionFragment,
"SELECTION");
transaction.commit();
}
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.addTab(actionBar.newTab().setText(R.string.menu)
.setTabListener(this));
actionBar.addTab(actionBar.newTab()
.setText(R.string.client_information).setTabListener(this));
sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
}
#Override
public void onSaveInstanceState(Bundle outState) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction transaction) {
switch (tab.getPosition()) {
case 0:
if (selectionFragment == null) {
selectionFragment = new SelectionFragment();
transaction.add(R.id.fragment_container_parent,
selectionFragment, "SELECTION");
} else {
transaction.attach(selectionFragment);
}
break;
case 1:
if (contactFragment == null) {
contactFragment = new ContactFragment();
transaction.add(R.id.fragment_container_parent,
contactFragment, "CONTACT");
} else {
transaction.attach(contactFragment);
}
break;
}
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction transaction) {
switch (tab.getPosition()) {
case 0:
if (selectionFragment != null)
transaction.detach(selectionFragment);
break;
case 1:
if (contactFragment != null)
transaction.detach(contactFragment);
break;
}
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction transaction) {
}
I can't understand what really happens to you, but here some tips:
When you rotate the screen Android destroy and rebuild all Fragment/Activity. So take a look in your onCreate, onDestroy...
If you're want a multiple screen app take a look here and create new layouts for each screen to make sure that your app will work fine.

Categories

Resources