Basically I'm making a tab activity that has fragments of other activities as the tabs. However when it runs, I am recieving a null pointer exception at the line:
final ActionBar actionBar = getActionBar();
Here is the whole activity. It is taken from the google sample.
public class MainActivity extends FragmentActivity implements ActionBar.TabListener {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sample_main);
// Set up the action bar. The navigation mode is set to NAVIGATION_MODE_TABS, which will
// cause the ActionBar to render a set of tabs. Note that these tabs are *not* rendered
// by the ViewPager; additional logic is lower in this file to synchronize the ViewPager
// state with the tab state. (See mViewPager.setOnPageChangeListener() and onTabSelected().)
// BEGIN_INCLUDE (set_navigation_mode)
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// END_INCLUDE (set_navigation_mode)
// BEGIN_INCLUDE (setup_view_pager)
// Create the adapter that will return a fragment for each of the three primary sections
// of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// END_INCLUDE (setup_view_pager)
// When swiping between different sections, select the corresponding tab. We can also use
// ActionBar.Tab#select() to do this if we have a reference to the Tab.
// BEGIN_INCLUDE (page_change_listener)
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// END_INCLUDE (page_change_listener)
// BEGIN_INCLUDE (add_tabs)
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.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
// callback (listener) for when this tab is selected.
actionBar.addTab(
actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
// END_INCLUDE (add_tabs)
}
/**
* Update {#link ViewPager} after a tab has been selected in the ActionBar.
*
* #param tab Tab that was selected.
* #param fragmentTransaction A {#link android.app.FragmentTransaction} for queuing fragment operations to
* execute once this method returns. This FragmentTransaction does
* not support being added to the back stack.
*/
// BEGIN_INCLUDE (on_tab_selected)
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, tell the ViewPager to switch to the corresponding page.
mViewPager.setCurrentItem(tab.getPosition());
}
// END_INCLUDE (on_tab_selected)
/**
* Unused. Required for {#link android.app.ActionBar.TabListener}.
*/
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
/**
* Unused. Required for {#link android.app.ActionBar.TabListener}.
*/
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
// BEGIN_INCLUDE (fragment_pager_adapter)
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages. This provides the data for the {#link ViewPager}.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
// END_INCLUDE (fragment_pager_adapter)
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
// BEGIN_INCLUDE (fragment_pager_adapter_getitem)
/**
* Get fragment corresponding to a specific position. This will be used to populate the
* contents of the {#link ViewPager}.
*
* #param position Position to fetch fragment for.
* #return Fragment for specified position.
*/
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
switch (position) {
case 0:
return new SearchPlayerFragment();
case 1:
return new SearchPlayerFragment();
case 2:
return new SearchPlayerFragment();
default:
return new SearchPlayerFragment();
}
}
// END_INCLUDE (fragment_pager_adapter_getitem)
// BEGIN_INCLUDE (fragment_pager_adapter_getcount)
/**
* Get number of pages the {#link ViewPager} should render.
*
* #return Number of fragments to be rendered as pages.
*/
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
// END_INCLUDE (fragment_pager_adapter_getcount)
// BEGIN_INCLUDE (fragment_pager_adapter_getpagetitle)
/**
* Get title for each of the pages. This will be displayed on each of the tabs.
*
* #param position Page to fetch title for.
* #return Title for specified page.
*/
#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;
}
// END_INCLUDE (fragment_pager_adapter_getpagetitle)
}
}
getActionBar() returns null because you are extending FragmentActivity.
Extend AppCompactActivity instead.
Try calling the Support Action Bar instead
getSupportActionBar();
I suggest you inherit from an ActionBarActivity instead of a FragmentActivity
Related
I'm at a complete loss.
I am trying to create a simple Tabbed Activity from the Android Studio wizard. If I run the project, the app hangs, and I get a thread exception error.
D/AndroidRuntime﹕ Shutting down VM
W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x4179cda0)
I/dalvikvm﹕ threadid=3: reacting to signal 3
I/dalvikvm﹕ Wrote stack traces to '/data/anr/traces.txt'
Which dumps a 4,000 line long stack trace.. which I haven't been able to gather much from after glancing it over a few times.
I've been over this code a hundred times and I can't find anything that stands out. I am able to add a tabbed activity to a brand new project, but when I add it to my current project, it fails to run. I don't know what other info I can provide.. I've been at this all day long.
Manifest:
<activity
android:name=".Blah"
android:label="#string/title_activity_blah" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
It creates a new ViewPager activity
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:id="#+id/pager"
android:layout_width="match_parent" android:layout_height="match_parent"
tools:context="com.test.testproject.Blah" />
With a default class:
public class Blah extends ActionBarActivity implements ActionBar.TabListener {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link 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}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ccs);
// Set up the action bar.
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.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 callback (listener) for when
// this tab is selected.
actionBar.addTab(
actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_ccs, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#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 onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}
#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 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;
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_ccs, container, false);
return rootView;
}
}
}
And a sample fragment:
<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" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.test.testproject.Blah$PlaceholderFragment">
<TextView android:id="#+id/section_label" android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
My application uses fragments and swipes to navigate different pages. I want to have an image button on each fragment activity so that when pressed first activity should be available. How can I do this. I tried viewpager.setcurrentitem option but it is only available in main activity. and in fragment activity viewpager is not available. I know there is way to by using android default property of sethome button. But I want an image button in each fragment.
This is my main activity
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
Tab tab = actionBar.newTab().setIcon(R.drawable.prf).setText(getString(R.string.title_section1)).setTabListener(this);
actionBar.addTab(tab, true);
tab = actionBar.newTab().setIcon(R.drawable.pack).setText(getString(R.string.title_section2)).setIcon(R.drawable.pack).setTabListener(this);
actionBar.addTab(tab);
tab = actionBar.newTab().setIcon(R.drawable.call).setText(getString(R.string.title_section3)).setTabListener(this);
actionBar.addTab(tab);
tab = actionBar.newTab().setIcon(R.drawable.prom).setText(getString(R.string.title_section4)).setTabListener(this);
actionBar.addTab(tab);
tab = actionBar.newTab().setIcon(R.drawable.infoin).setText(getString(R.string.title_section5)).setTabListener(this);
actionBar.addTab(tab);
}
#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 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 onTabUnselected(ActionBar.Tab tab,FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab,FragmentTransaction fragmentTransaction) {
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0 :
return new Home();
case 1:
return new info();
case 2:
return new Plan();
}
return null;
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
}
Use callback mechanism through Interface and send message back to Activity of what you want to do on click of ImageButton. Same mechanism is good for fragments communication with each other.
I'm using the ActionBar and tab navigation with Fragments.
Each tab contain a Fragment FragmentX with a ListView, and when clicking on an item of a list FragmentX is replaced by another Fragment FragmentY with the detail of the item.
How can I set the Up button of the ActionBar to load FragmentX when I'm in FragmentY?
The doc shows that the navigation should be done between Activities, but the ActionBar's navigation tabs allow to navigate between Fragments, not Activities.
What am I missing?
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. 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}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.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 callback (listener) for when
// this tab is selected.
LinearLayout view = (LinearLayout) getLayoutInflater().inflate(R.layout.tab, null);
ImageView icon = (ImageView) view.findViewById(R.id.icon);
icon.setImageResource(tabIconList[i]);
TextView title = (TextView) view.findViewById(R.id.title);
title.setText(tabTitleList[i]);
actionBar.addTab(actionBar.newTab()
.setCustomView(view)
.setTabListener(this));
}
}
#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 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 onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment = null;
switch(position){
case 0:
fragment = new MyListFragment1();
break;
case 1:
fragment = new MyListFragment2();
break;
case 2:
fragment = new MyListFragment3();
break;
default: fragment = new MyListFragment1();
}
return fragment;
}
#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 getString(R.string.title1).toUpperCase(l);
case 1:
return getString(R.string.title2).toUpperCase(l);
case 2:
return getString(R.string.title3).toUpperCase(l);
}
return null;
}
}
}
Active up navigation when you load FragmentY.
Then intercept up navigation on onOptionsItemSelected, just popup the backstack and launch your FragmentX.
I've done a rapid search on SO and i found this, wich inspired me.
I didn't use the ActionBar in the end. Too many constraints (I had another issue and I wanted to add a View above the ActionBar, which seemed complicated).
It was much simpler doing my own layout from scratch.
I have completed so many tutorials on this, yet I still have not found one which has helped. The problem is I am using Tabs (with swipe), and want each tab to load a different class (some tabs will have access to different data and databases, each tab will be completely different). I know I need to use fragments, but the tutorials just get each fragment to display 'Tab 1', 'Tab 2', etc. Does anybody know a tutorial which explains how to do this? Its driving me crazy! I´ve spent so many hours trying to figure this out. Tks
Here is how i do it:
My MainActivity with my ViewPager:
public class MainActivity extends SherlockFragmentActivity implements
ActionBar.TabListener {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. 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}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar.
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.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 callback (listener) for when
// this tab is selected.
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#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 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) {
Fragment fragment = null;
if (position == 0) {
fragment = new Tab1Fragment();
}
if (position == 1) {
fragment = new Tab2Fragment();
}
if (position == 2) {
fragment = new Tab3Fragment();
}
if (position == 3) {
fragment = new Tab4Fragment();
}
return fragment;
}
#Override
public int getCount() {
// Show 4 total pages.
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase();
case 1:
return getString(R.string.title_section2).toUpperCase();
case 2:
return getString(R.string.title_section3).toUpperCase();
case 3:
return getString(R.string.title_section4).toUpperCase();
}
return null;
}
}
}
This loads a different fragment depending on which tab is selected. For example, if tab 2 is selected, it loads Tab2Fragment.java
I am using ActionBar using Sherlock library. Implemented Tabs also in this app.
Now, when I am using the NavigationList in the ActionBar, I lost my Tab fragments. For using ListNavigation in the ActionBar I have used:
mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
& before this I was using mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); for tabs but no list.
Now, I want to use both , NavigationList and Tab Fragments
public class MainActivity extends SherlockFragmentActivity implements OnNavigationListener {
ActionBar mActionBar;
ViewPager mPager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/** Getting a reference to action bar of this activity */
mActionBar = getSupportActionBar();
/** Set tab navigation mode */
mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
//mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
SpinnerAdapter mSpinnerAdapter = ArrayAdapter.createFromResource(
this,
R.array.locations,
android.R.layout.simple_spinner_item);
mActionBar.setListNavigationCallbacks(mSpinnerAdapter, this);
mActionBar.setIcon(R.drawable.app_icon);
/** Getting a reference to ViewPager from the layout */
mPager = (ViewPager) findViewById(R.id.pager);
/** Getting a reference to FragmentManager */
FragmentManager fm = getSupportFragmentManager();
/** Defining a listener for pageChange */
ViewPager.SimpleOnPageChangeListener pageChangeListener = new ViewPager.SimpleOnPageChangeListener(){
#Override
public void onPageSelected(int position) {
super.onPageSelected(position);
mActionBar.setSelectedNavigationItem(position);
}
};
/** Setting the pageChange listner to the viewPager */
mPager.setOnPageChangeListener(pageChangeListener);
/** Creating an instance of FragmentPagerAdapter */
MyFragmentPagerAdapter fragmentPagerAdapter = new MyFragmentPagerAdapter(fm);
/** Setting the FragmentPagerAdapter object to the viewPager object */
mPager.setAdapter(fragmentPagerAdapter);
mActionBar.setDisplayShowTitleEnabled(true);
/** Defining tab listener */
ActionBar.TabListener tabListener = new ActionBar.TabListener() {
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
mPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
};
/** Creating Android Tab */
Tab tab = mActionBar.newTab()
.setText("Android")
.setIcon(R.drawable.android)
.setTabListener(tabListener);
mActionBar.addTab(tab);
/** Creating Apple Tab */
tab = mActionBar.newTab()
.setText("Apple")
.setIcon(R.drawable.apple)
.setTabListener(tabListener);
mActionBar.addTab(tab);
}
}
MyFragmentPagerAdapter.java
public class MyFragmentPagerAdapter extends FragmentPagerAdapter{
final int PAGE_COUNT = 2;
/** Constructor of the class */
public MyFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
/** This method will be invoked when a page is requested to create */
#Override
public Fragment getItem(int arg0) {
Bundle data = new Bundle();
switch(arg0){
/** Android tab is selected */
case 0:
AndroidFragment androidFragment = new AndroidFragment();
data.putInt("current_page", arg0+1);
androidFragment.setArguments(data);
return androidFragment;
/** Apple tab is selected */
case 1:
AppleFragment appleFragment = new AppleFragment();
data.putInt("current_page", arg0+1);
appleFragment.setArguments(data);
return appleFragment;
}
return null;
}
/** Returns the number of pages */
#Override
public int getCount() {
return PAGE_COUNT;
}
}
And the other two classes:
1) public class AppleFragment extends SherlockListFragment
2) public class AndroidFragment extends SherlockListFragment
Please suggest me, why I am losing my Tabs on adding List to ActionBar.
You can't use both NAVIGATION_MODE_LIST and NAVIGATION_MODE_TABS at the same time. You can use just a navigation mode at a time.
Usage of list navigation and tabs in the ActionBar is mutually exclusive, you just can use only one.
If you want to use both list and tabs, you have to use different implementation for at least one of them. For tabs you can use ViewPagerIndicator. Spinner in the ActionBar can be created several ways:
use custom view to create the spinner
use actionLayout or actionViewClass for a menu item
use ActionProvider for a menu item
Edit:
In your case the easiest adjustment is to use ViewPagerIndicator instead of ActionBar tabs. Changing list navigation requires more work.
The web page of the ViewPagerIndicator project shows some example setup which you should take a look at. The project's GitHub page has many samples which shows how to use various setups of the library. I guess what you are looking for is TabPageIndicator, so take a look at this sample (notice that the tabs' titles are created in the FragmentPagerAdapter, you don't need ActionBar.Tab and ActionBar.TabListener anymore).