These are the screenshots of my application,
http://i.stack.imgur.com/3GYAc.png ==> after loading the list from remote server the list is populated.
The problem for me is this,
When i move to the title Android - third tab(refer link) and switch back to java tab, the data is loading again.
How to make it load it single time and save it, so that it doesn't load every time?
The main activity is fragmentactivity which listens to tabadapter for changes in tabs.
This one is page adapter..
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
// Top Rated fragment activity
return new TopRatedFragment2();
case 1:
// Games fragment activity
return new GamesFragment();
case 2:
// Movies fragment activity
return new MoviesFragment();
}
return null;
}
This one is fragmentActivity which uses page adapter
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.messages_layout);
// Initilization
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener((TabListener) this));
}
/**
* 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 onTabReselected(Tab arg0, FragmentTransaction arg1) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(Tab arg0, FragmentTransaction arg1) {
int position = mAdapter.getItemPosition(arg0);//;findItemPosition(arg0.getPosition());
viewPager=(getCurrentFocus()).ggetFragment(arg0, null);
viewPager.setCurrentItem(arg0.getPosition());
}
According to revision 4 of the Support Package, a method was added to ViewPager which allows you to specify the number of offscreen pages to use, rather than the default which is 1.
so you can load page rightside when move.
In your case, you want to specify 2, so that when you are on the third page, the first one is not destroyed, and vice-versa.
mViewPager = (ViewPager)findViewById(R.id.pager);
mViewPager.setOffscreenPageLimit(2);
Thats it....
I assume you are creating the Fragment each time the tab is loaded like
JavaFragment java=new JavaFragment();
Try to declare it as global and create a new instance only if the object is null
like:
JavaFragment java;
Fragment getItem(int index)
{
case 0:
if(java==null){
java=new javaFragment();}
return java;
break;
case 1:...........
..............
.............
}
Related
First of all I would like to thank the stackoverflow community. Thanks to you I solved so much problems! Usually I bang my head over the wall for hours and I find the solution here (98% percent of the time). This time I would like to share my problem.
This is the first app I'm developing. I have one activity (is this bad?). My app structure is the following: Nav drawer which contains four items - two viewpagers and two static fragments. The viewpagers contains lists with data and if you click on one of the items from the list you are present with a detail page which again is a viewpager. When you are on the detail page you can click and advance to other fragment. The problem is that when I advance to the other fragment onSavedInstance is not called for the viewpagerdetails and I can't retain the fragment state. onSavedInstance will be called if I pass to the FragmentPagerAdapter getFragmentManager(), instead of getChildFragmentManager(), but if I do this when I navigate back, the viewpager items are blank. I have tried using FragmentStatePagerAdapter, but when I click back from the 'other fragment' to return to viewpager details the app crashes with the following error: Fragment no longer exists for key f0: index 0. I have looked over the internet, but I didn't found a working solution. Some say that the problem is from the adapter, but I tried this solution and it didn't work. Also I want to manually retain my fragment state, please don't offer me the fix with the configchanges in the app manifest. I have tried to call onSavedInstanceState from the onStop method, but when I return to the fragment the saved state is empty. Should I implement this with a static variable in my mainActivity?
FragmentPagerAdapter:
public class DetailsSlideAdapter extends FragmentPagerAdapter {
private String[] navMenuTitles;
private FragmentManager manager;
private FragmentTransaction mCurTransaction = null;
private Resources res;
public DetailsSlideAdapter(FragmentManager fm, Resources res) {
super(fm);
this.manager = fm;
navMenuTitles = res.getStringArray(R.array.detailTabs);
this.res = res;
}
#Override
public int getCount() {
return 3;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
DetailsInfo info = new DetailsInfo();
return info;
case 1:
DetailsCast cast = new DetailsCast();
return cast;
case 2:
DetailsOverview overview = new DetailsOverview();
return overview;
default:
return null;
}
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return navMenuTitles[0];
case 1:
return navMenuTitles[1];
case 2:
return navMenuTitles[2];
default:
return navMenuTitles[1];
}
}
Viewpager details:
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// Get the ViewPager and set it's PagerAdapter so that it can display items
DetailsSlideAdapter = new DetailsSlideAdapter(getChildFragmentManager(), getResources());
mViewPager = (ViewPager) rootView.findViewById(R.id.DetailsPager);
mViewPager.setOffscreenPageLimit(3);
mViewPager.setAdapter(DetailsSlideAdapter);
// Give the SlidingTabLayout the ViewPager, this must be done AFTER the ViewPager has had
// it's PagerAdapter set.
mSlidingTabLayout = (DetailsSlidingTabLayout) rootView.findViewById(R.id.sliding_tabs);
mSlidingTabLayout.setViewPager(mViewPager);
mSlidingTabLayout.setSelectedIndicatorColors(getResources().getColor(R.color.tabSelected));
}
If other code is needed I will post it. Thanks.
EDIT using FragmentStateAdapter:
App crashes: Fragment no longer exists for key f0: index 0. On the internet people say that the problem is from the adapter, but I tried this solution and it didn't work. Code:
public class DetailsSlideAdapter extends FragmentStatePagerAdapter {
private String[] navMenuTitles;
private FragmentManager manager;
private FragmentTransaction mCurTransaction = null;
private Resources res;
SparseArray<Fragment> registeredFragments = new SparseArray<Fragment>();
public DetailsSlideAdapter(FragmentManager fm, Resources res) {
super(fm);
this.manager = fm;
navMenuTitles = res.getStringArray(R.array.detailTabs);
this.res = res;
}
#Override
public int getCount() {
return 3;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
DetailsInfo info = new DetailsInfo();
return info;
case 1:
DetailsCast cast = new DetailsCast();
return cast;
case 2:
DetailsOverview overview = new DetailsOverview();
return overview;
default:
return null;
}
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return navMenuTitles[0];
case 1:
return navMenuTitles[1];
case 2:
return navMenuTitles[2];
default:
return navMenuTitles[1];
}
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
registeredFragments.put(position, fragment);
return fragment;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
registeredFragments.remove(position);
super.destroyItem(container, position, object);
}
public Fragment getRegisteredFragment(int position) {
return registeredFragments.get(position);
}
Have you seen this? FragmentStatePagerAdapter
From the Docs:
Implementation of PagerAdapter that uses a Fragment to manage each
page. This class also handles saving and restoring of fragment's
state.
I have this weird issue with the viewPager. When I swipe from one fragment to the next and then swipe back, the layout is correct, but when pressing an element (Listview item for example), the previous java code still did not update with the view. I don't know if I can explain this any better, as it works when I play with the swipe until the fragment works like its supposed to. here is my code:
Main.Java:
public class Main extends FragmentActivity {
SectionsPagerAdapter mAdapter;
ViewPager mViewPager;
// for alert transitions
AlertDialog dialog;
// share button
private ShareActionProvider mShareActionProvider;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// set up button
getActionBar().setDisplayHomeAsUpEnabled(true);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mAdapter);
mViewPager.setPageTransformer(true, new DepthPageTransformer());
}
#Override
public void onBackPressed() {
if (mViewPager.getCurrentItem() == 0) {
// If the user is currently looking at the first step, allow the system to handle the
// Back button. This calls finish() on this activity and pops the back stack.
super.onBackPressed();
} else {
// Otherwise, select the previous step.
mViewPager.setCurrentItem(mViewPager.getCurrentItem() - 1);
}
}
}
SectionsPagerAdapter.java:
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
return new Important();
case 1:
return new Propositions();
case 2:
return new Information();
}
return null;
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return ("Important Dates").toUpperCase(l);
case 1:
return ("Props").toUpperCase(l);
case 2:
return ("Information").toUpperCase(l);
}
return null;
}
}
The Fragments all use the onCreateView() method.
Thanks in advance for your help!
Maybe a late response, but I've experienced the same issue.
The problem was the DepthPageTransformer you are using from the Android Developers example for PageTransformer.
There is a bug with stacking fragments and layer priority, I assume. By fixing the custom PageTransformer will fix your "swipe back" issue. Or if you don't mind the animation, just remove your custom PageTransformer and use the default animation (by adding nothing).
When I start a new android activity the methods that are being called before the activity actually appears in the screen are onCreate() -> onStart() -> onResume()? or there are some more called before I see the activity on the screen?
I've written an application in which I overrode only the onCreate() method from the three I mentioned before, but from some reason the application crashes, although the onCreate() finishes successfuly.
onCreate method:
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.d("SMARTGAN", "starting ChildActivity onCreate()");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_child);
// find child for the activity
child = (Child) getIntent().getSerializableExtra(MainActivity.CHILD);
// initialization
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
adapter = new TabsPagerAdapter(getSupportFragmentManager(), child);
viewPager.setAdapter(adapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// set action bar properties
actionBar.setTitle(child.getName());
actionBar.setIcon(R.drawable.ic_action_person);
// adding the tabs to the action bar
for (int i = 0; i < tabs.length; i++) {
actionBar.addTab(actionBar.newTab().setText(tabs[i])
.setTabListener(this));
}
// set OnPageChangeListener so that whenever the user changes the page
// the selected tab in the action bar also changes
viewPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) { }
#Override
public void onPageScrollStateChanged(int arg0) { }
});
Log.d("SMARTGAN", "ChildActivity onCreate completed");
}
Maybe you will find your answer in this android activity lifecycle
Did you add your activity to the AndroidManifest.xml file? The second way: maybe you have problem with you content view (when setting view with setContentView() method)?
I am referring to this tutorial for making simple tabs in Android.
MainActivity.java
public class MainActivity extends Activity {
// Declare Tab Variable
ActionBar.Tab Tab1, Tab2, Tab3;
Fragment fragmentTab1 = new FragmentTab1();
Fragment fragmentTab2 = new FragmentTab2();
Fragment fragmentTab3 = new FragmentTab3();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar actionBar = getActionBar();
// Hide Actionbar Icon
actionBar.setDisplayShowHomeEnabled(false);
// Hide Actionbar Title
actionBar.setDisplayShowTitleEnabled(false);
// Create Actionbar Tabs
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Set Tab Icon and Titles
Tab1 = actionBar.newTab().setIcon(R.drawable.tab1);
Tab2 = actionBar.newTab().setText("Tab2");
Tab3 = actionBar.newTab().setText("Tab3");
// Set Tab Listeners
Tab1.setTabListener(new TabListener(fragmentTab1));
Tab2.setTabListener(new TabListener(fragmentTab2));
Tab3.setTabListener(new TabListener(fragmentTab3));
// Add tabs to actionbar
actionBar.addTab(Tab1);
actionBar.addTab(Tab2);
actionBar.addTab(Tab3);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
fragmenttab1.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="#string/Fragment1" />
</RelativeLayout>
Similarly other XML & Java files.
The output is:
Clearly tabs are not uniformly distributed, since empty space is left on right hand side, all seems to be pushed to left corner.
How to make this happen?
Try this code:-
Main Activity
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the primary sections of the app.
*/
public static class AppSectionsPagerAdapter extends FragmentPagerAdapter {
public AppSectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return 4;
}
#Override
public Fragment getItem(int i) {
switch (i) {
case 0:
// The first section of the app is the most interesting -- it
// offers
// a launchpad into the other demonstrations in this example
// application.
i++;
return new LaunchpadSectionFragment();
case 1:
// The first section of the app is the most interesting -- it
// offers
// a launchpad into the other demonstrations in this example
// application.
i++;
return new LaunchpadSectionFragment();
case 2:
// The first section of the app is the most interesting -- it
// offers
// a launchpad into the other demonstrations in this example
// application.
i++;
return new LaunchpadSectionFragment();
case 3:
// The first section of the app is the most interesting -- it
// offers
// a launchpad into the other demonstrations in this example
// application.
i++;
return new LaunchpadSectionFragment();
case 4:
// The first section of the app is the most interesting -- it
// offers
// a launchpad into the other demonstrations in this example
// application.
i++;
return new LaunchpadSectionFragment();
default:
// The other sections of the app are dummy placeholders.
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, i + 1);
fragment.setArguments(args);
return fragment;
}
}
#Override
public CharSequence getPageTitle(int position) {
String name = null;
switch (position) {
case 0:
name = "School Info";
break;
case 1:
name = "Picture (s)";
break;
default:
name = "Group";
break;
}
return name;
}
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public static class DummySectionFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_section_dummy,
container, false);
Bundle args = getArguments();
((TextView) rootView.findViewById(android.R.id.text1))
.setText(getString(R.string.dummy_section_text,
args.getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
/**
* A fragment that launches other parts of the demo application.
*/
public static class LaunchpadSectionFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(
R.layout.fragment_section_launchpad, container, false);
// Demonstration of a collection-browsing activity.
rootView.findViewById(R.id.demo_collection_button)
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(),
CollectionDemoActivity.class);
startActivity(intent);
}
});
// Demonstration of navigating to external activities.
rootView.findViewById(R.id.demo_external_activity)
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Create an intent that asks the user to pick a
// photo, but using
// FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET, ensures that
// relaunching
// the application from the device home screen does
// not return
// to the external activity.
// Intent externalActivityIntent = new Intent(
// Intent.ACTION_PICK);
// externalActivityIntent.setType("image/*");
// externalActivityIntent
// .addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
// startActivity(externalActivityIntent);
System.exit(0);
}
});
return rootView;
}
}
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the three primary sections of the app. We use a
* {#link android.support.v4.app.FragmentPagerAdapter} derivative, which
* will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
AppSectionsPagerAdapter mAppSectionsPagerAdapter;
/**
* The {#link ViewPager} that will display the three primary sections of the
* app, one at a time.
*/
ViewPager mViewPager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create the adapter that will return a fragment for each of the three
// primary sections
// of the app.
mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(
getSupportFragmentManager());
// Set up the action bar.
final ActionBar actionBar = getActionBar();
// Specify that the Home/Up button should not be enabled, since there is
// no hierarchical
// parent.
actionBar.setHomeButtonEnabled(false);
// Specify that we will be displaying tabs in the action bar.
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Set up the ViewPager, attaching the adapter and setting up a listener
// for when the
// user swipes between sections.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mAppSectionsPagerAdapter);
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// When swiping between different app sections, select
// the corresponding tab.
// We can also use ActionBar.Tab#select() to do this if
// we have a reference to the
// Tab.
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mAppSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter.
// Also specify this Activity object, which implements the
// TabListener interface, as the
// listener for when this tab is selected.
actionBar.addTab(actionBar.newTab()
.setText(mAppSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#Override
public void onTabReselected(Tab tab, android.app.FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(Tab tab, android.app.FragmentTransaction ft) {
// TODO Auto-generated method stub
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, android.app.FragmentTransaction ft) {
// TODO Auto-generated method stub
}
}
CollectionDemoActivity
public class CollectionDemoActivity extends FragmentActivity {
/**
* A {#link android.support.v4.app.FragmentStatePagerAdapter} that returns a
* fragment representing an object in the collection.
*/
public static class DemoCollectionPagerAdapter extends
FragmentStatePagerAdapter {
public DemoCollectionPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
// For this contrived example, we have a 10-object collection.
return 10;
}
#Override
public Fragment getItem(int i) {
Fragment fragment = new DemoObjectFragment();
Bundle args = new Bundle();
args.putInt(DemoObjectFragment.ARG_OBJECT, i + 1); // Our object is
// just an
// integer :-P
fragment.setArguments(args);
return fragment;
}
#Override
public CharSequence getPageTitle(int position) {
return "Q. Set " + (position + 1);
}
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public static class DemoObjectFragment extends Fragment {
public static final String ARG_OBJECT = "Question Set";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(
R.layout.fragment_collection_object, container, false);
Bundle args = getArguments();
((TextView) rootView.findViewById(android.R.id.text1))
.setText("Q.Set "
+ Integer.toString(args.getInt(ARG_OBJECT)));
return rootView;
}
}
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments representing each object in a collection. We use a
* {#link android.support.v4.app.FragmentStatePagerAdapter} derivative,
* which will destroy and re-create fragments as needed, saving and
* restoring their state in the process. This is important to conserve
* memory and is a best practice when allowing navigation between objects in
* a potentially large collection.
*/
DemoCollectionPagerAdapter mDemoCollectionPagerAdapter;
/**
* The {#link android.support.v4.view.ViewPager} that will display the
* object collection.
*/
ViewPager mViewPager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_collection_demo);
// Create an adapter that when requested, will return a fragment
// representing an object in
// the collection.
//
// ViewPager and its adapters use support library fragments, so we must
// use
// getSupportFragmentManager.
mDemoCollectionPagerAdapter = new DemoCollectionPagerAdapter(
getSupportFragmentManager());
// Set up action bar.
final ActionBar actionBar = getActionBar();
// Specify that the Home button should show an "Up" caret, indicating
// that touching the
// button will take the user one step up in the application's hierarchy.
actionBar.setDisplayHomeAsUpEnabled(true);
// Set up the ViewPager, attaching the adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mDemoCollectionPagerAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This is called when the Home (Up) button is pressed in the action
// bar.
// Create a simple intent that starts the hierarchical parent
// activity and
// use NavUtils in the Support Package to ensure proper handling of
// Up.
Intent upIntent = new Intent(this, MainActivity.class);
if (NavUtils.shouldUpRecreateTask(this, upIntent)) {
// This activity is not part of the application's task, so
// create a new task
// with a synthesized back stack.
TaskStackBuilder.from(this)
// If there are ancestor activities, they should be added here.
.addNextIntent(upIntent).startActivities();
finish();
} else {
// This activity is part of the application's task, so simply
// navigate up to the hierarchical parent activity.
NavUtils.navigateUpTo(this, upIntent);
}
return true;
case R.id.menuCancel:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
Please use FragmentActivity instead of Activity, it will be worthy. And refer this documentation, it helps the beginners very well.
http://developer.android.com/guide/topics/ui/actionbar.html
It depends on the emulator - i mean name of the device in the emulator
try other one with different API level
There is no problem with the code
I am studying the code below, but I was able to compile it successfully, my problem is using the code I want to have a series of connected Activities in one tab section. Please give your suggestions and ideas abut this. The whole source came from link. Your help and explanation is greatly appreciated. THanks!
Tab 1
-Activity A -> Activity B -> Activity C
Here: Effective Navigation
MainActivity.java
public class MainActivity extends FragmentActivity implements ActionBar.TabListener {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide fragments for each of the
* three primary sections of the app. We use a {#link android.support.v4.app.FragmentPagerAdapter}
* derivative, which will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
AppSectionsPagerAdapter mAppSectionsPagerAdapter;
/**
* The {#link ViewPager} that will display the three primary sections of the app, one at a
* time.
*/
ViewPager mViewPager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create the adapter that will return a fragment for each of the three primary sections
// of the app.
mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(getSupportFragmentManager());
// Set up the action bar.
final ActionBar actionBar = getActionBar();
// Specify that the Home/Up button should not be enabled, since there is no hierarchical
// parent.
actionBar.setHomeButtonEnabled(false);
// Specify that we will be displaying tabs in the action bar.
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Set up the ViewPager, attaching the adapter and setting up a listener for when the
// user swipes between sections.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mAppSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// When swiping between different app sections, select the corresponding tab.
// We can also use ActionBar.Tab#select() to do this if we have a reference to the
// Tab.
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mAppSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by the adapter.
// Also specify this Activity object, which implements the TabListener interface, as the
// listener for when this tab is selected.
actionBar.addTab(
actionBar.newTab()
.setText(mAppSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to one of the primary
* sections of the app.
*/
public static class AppSectionsPagerAdapter extends FragmentPagerAdapter {
public AppSectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
switch (i) {
case 0:
// The first section of the app is the most interesting -- it offers
// a launchpad into the other demonstrations in this example application.
return new LaunchpadSectionFragment();
default:
// The other sections of the app are dummy placeholders.
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, i + 1);
fragment.setArguments(args);
return fragment;
}
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
return "Section " + (position + 1);
}
}
/**
* A fragment that launches other parts of the demo application.
*/
public static class LaunchpadSectionFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_section_launchpad, container, false);
// Demonstration of a collection-browsing activity.
rootView.findViewById(R.id.demo_collection_button)
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(), CollectionDemoActivity.class);
startActivity(intent);
}
});
// Demonstration of navigating to external activities.
rootView.findViewById(R.id.demo_external_activity)
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Create an intent that asks the user to pick a photo, but using
// FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET, ensures that relaunching
// the application from the device home screen does not return
// to the external activity.
Intent externalActivityIntent = new Intent(Intent.ACTION_PICK);
externalActivityIntent.setType("image/*");
externalActivityIntent.addFlags(
Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
startActivity(externalActivityIntent);
}
});
return rootView;
}
}
/**
* A dummy fragment representing a section of the app, but that simply displays dummy text.
*/
public static class DummySectionFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_section_dummy, container, false);
Bundle args = getArguments();
((TextView) rootView.findViewById(android.R.id.text1)).setText(
getString(R.string.dummy_section_text, args.getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
}
CollectionDemoActivity.java
public class CollectionDemoActivity extends FragmentActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide fragments representing
* each object in a collection. We use a {#link android.support.v4.app.FragmentStatePagerAdapter}
* derivative, which will destroy and re-create fragments as needed, saving and restoring their
* state in the process. This is important to conserve memory and is a best practice when
* allowing navigation between objects in a potentially large collection.
*/
DemoCollectionPagerAdapter mDemoCollectionPagerAdapter;
/**
* The {#link android.support.v4.view.ViewPager} that will display the object collection.
*/
ViewPager mViewPager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_collection_demo);
// Create an adapter that when requested, will return a fragment representing an object in
// the collection.
//
// ViewPager and its adapters use support library fragments, so we must use
// getSupportFragmentManager.
mDemoCollectionPagerAdapter = new DemoCollectionPagerAdapter(getSupportFragmentManager());
// Set up action bar.
final ActionBar actionBar = getActionBar();
// Specify that the Home button should show an "Up" caret, indicating that touching the
// button will take the user one step up in the application's hierarchy.
actionBar.setDisplayHomeAsUpEnabled(true);
// Set up the ViewPager, attaching the adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mDemoCollectionPagerAdapter);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This is called when the Home (Up) button is pressed in the action bar.
// Create a simple intent that starts the hierarchical parent activity and
// use NavUtils in the Support Package to ensure proper handling of Up.
Intent upIntent = new Intent(this, MainActivity.class);
if (NavUtils.shouldUpRecreateTask(this, upIntent)) {
// This activity is not part of the application's task, so create a new task
// with a synthesized back stack.
TaskStackBuilder.from(this)
// If there are ancestor activities, they should be added here.
.addNextIntent(upIntent)
.startActivities();
finish();
} else {
// This activity is part of the application's task, so simply
// navigate up to the hierarchical parent activity.
NavUtils.navigateUpTo(this, upIntent);
}
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A {#link android.support.v4.app.FragmentStatePagerAdapter} that returns a fragment
* representing an object in the collection.
*/
public static class DemoCollectionPagerAdapter extends FragmentStatePagerAdapter {
public DemoCollectionPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
Fragment fragment = new DemoObjectFragment();
Bundle args = new Bundle();
args.putInt(DemoObjectFragment.ARG_OBJECT, i + 1); // Our object is just an integer :-P
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
// For this contrived example, we have a 100-object collection.
return 100;
}
#Override
public CharSequence getPageTitle(int position) {
return "OBJECT " + (position + 1);
}
}
/**
* A dummy fragment representing a section of the app, but that simply displays dummy text.
*/
public static class DemoObjectFragment extends Fragment {
public static final String ARG_OBJECT = "object";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_collection_object, container, false);
Bundle args = getArguments();
((TextView) rootView.findViewById(android.R.id.text1)).setText(
Integer.toString(args.getInt(ARG_OBJECT)));
return rootView;
}
}
}
I learned that having connected Activities is deprecated and just use nested fragments instead.
From Docu:
Nested Fragments - Fragments have its own life cycle like an activity.