Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialaxel treza
3,702 PointsFeeling lost regarding default fragments following the ADT update.
Hey Everyone,
Following the ADT update it looks like it is difficult to modify tabs from the template as shown on the tutorial. It seems that the interface ActionBar.TabListener does not appear anymore (and bugs appear when I try to add it). Same as the DummySectionFragment class. It becomes difficult to carry on with lesson. :-( It would be very nice if somebody could advise on this matter. Another way certainly exist but I feel pretty much lost.
13 Answers
Ben Jakuben
Treehouse TeacherThis has been an unfortunate change causing problems for students before they even get started. The good news is that you should be okay once you get past it.
I'm going to add some notes to that video, but everything should still apply for the most part. Are you having trouble following along with anything specific? The ActionBar.TabListener should still appear, so I don't know why that is missing for you.
Jeremy Broutin
1,951 Points14/06/2014: I would like to share a comment of how I worked around this issue as well, as I followed each of the comments to fully solve the problem. It's basically the same steps as described by Seye just above + two more shared by Ben in this thread =>
SectionsPagerAdapter class
Replace the imports to finally have the below ones (and ONLY those ones):
- import android.support.v4.app.Fragment;
- import android.support.v4.app.FragmentManager;
- import android.support.v4.app.FragmentPagerAdapter;
- import android.content.Context;
- import java.util.locale
MainActivity class
1/ change the definition of mSectionsPagerAdapter from
- new SectionsPagerAdapter(this, getFragmentManager())
- to
- new SectionsPagerAdapter(this, getSupportFragmentManager())
2/ (if it's not already the case) change the class extension from
- public class MainActivity extends Activity
- to
- public class MainActivity extends FragmentActivity
3/ add the following import to your list:
- import android.support.v4.app.FragmentActivity;
Hope it can help many students working on Android Studio :)
Ben Jakuben
Treehouse TeacherThanks for sharing, Jeremy! I updated my notes with these clear instructions.
Seye Kuyinu
2,581 PointsBen Jakuben I really think you should put a teacher's note. This cost me about 3hours of searching, cmd+z -ing. :)
Ben Jakuben
Treehouse TeacherThanks for the heads up - will do right now!
axel treza
3,702 PointsHello and thanks for the swift reply,
It looks like I have made a mistake from the very beginning. In the Setting Up the Project" video, I did not paid attention to your note regarding the Blank activity Navigation Type. I should have selected Action Bar Tabs (with ViewPager). That is the reason why the ActionBar.Listener did not appear in my previous attempt.
Unfortunately after having re started the project, with the right settings, I still have trouble to finish the "Modifying Fragments from the Template" tutorial.
Modifying Fragments from the Template
in the SectionsPagerAdapter.java file, when I return the new InboxFragment() I have an error message "Type mismatch: cannot convert from InboxFragment to Fragment". I cannot execute the code and really don t know where the issue comes from. (line 24)
SectionsPagerAdapter.java
package com.test.ribbit;
import java.util.Locale;
import android.app.FragmentManager;
import android.content.Context;
import android.support.v13.app.FragmentPagerAdapter;
import android.support.v4.app.Fragment;
/**
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
protected Context mContext;
public SectionsPagerAdapter(Context context, FragmentManager fm) {
super(fm);
mContext = context;
}
@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 new InboxFragment();
}
@Override
public int getCount() {
// Show 2 total pages.
return 2;
}
@Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return mContext.getString(R.string.title_section1).toUpperCase(l);
case 1:
return mContext.getString(R.string.title_section2).toUpperCase(l);
}
return null;
}
}
InboxFragment.java
package com.test.ribbit;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
// Inbox will be a list of messages
public class InboxFragment extends ListFragment{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_inbox, container,
false);
return rootView;
}
}
Ben Jakuben
Treehouse TeacherThis message usually has to do with having the wrong imports for Fragments in one of the places. What makes it tricky is that we need to use the support versions of Fragments to work with the ViewPager. They work the same exact way, but one wrong import statement, and bam, your project won't work.
Try this for me: In SectionsPagerAdapter.java, delete these lines:
import android.app.FragmentManager;
import android.support.v13.app.FragmentPagerAdapter;
import android.support.v4.app.Fragment;
And replace them with these:
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
You may need to reorganize imports afterward just to make sure it's all cleaned up correctly. Let me know what happens and we'll go from there.
Harry James
14,780 PointsHi Ben,
I had this exact same problem and your fix here worked perfect for me.
Thanks a lot!
axel treza
3,702 PointsIt wooooooooorks!!!!!!!!
Once again thanks a lot. I needed to extend FragmentActivity. Where was my head? Thanks for your time. I can carry on now.
Seye Kuyinu
2,581 PointsHere is how I came to the solution:
All the imports for my SectionsPagerAdapter class were this:
import java.util.Locale;
import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter;
import android.content.Context;
Then in MainActivity, as Ben had said, I changed that line to:
mSectionsPagerAdapter = new SectionsPagerAdapter(this,getSupportFragmentManager());
axel treza
3,702 PointsI understand, I have added the right imports and the error message has disappeared in SectionsPagerAdapter.java And I did delete the android-support-v13 from the library.
A new error message appear in the MainActivity.java "The constructor SectionsPagerAdapter(MainActivity, FragmentManager) is undefined" (line 57)
MainActivity.java
package com.test.ribbit;
import android.app.ActionBar;
import android.app.Activity;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import com.parse.ParseUser;
// Main Activity is the first activity the user will see when login into the app.
// All the activity will be in portrait orientation
public class MainActivity extends Activity implements ActionBar.TabListener {
public static final String TAG = MainActivity.class.getSimpleName();
/**
* 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.v13.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);
// Start the login activity when the app launch
// check if the user is logged in session
ParseUser currentUser = ParseUser.getCurrentUser();
if (currentUser == null) {
navigateToLogin();
} else {
Log.i(TAG, currentUser.getUsername());
}
// 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 activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(this, getFragmentManager());
// 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));
}
}
private void navigateToLogin() {
Intent intent = new Intent(this, LoginActivity.class);
// Navigation of the different activities according to order of use (avoid to go back to the main activity when tapping on the back button)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
@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
// Log out from the app
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 itemId = item.getItemId();
if (itemId == R.id.action_logout) {
ParseUser.logOut();
navigateToLogin();
}
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 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_main, container,
// false);
// TextView textView = (TextView) rootView
// .findViewById(R.id.section_label);
// textView.setText(Integer.toString(getArguments().getInt(
// ARG_SECTION_NUMBER)));
// return rootView;
// }
// }
when I launch the app, the emulator crash and I have the following error message in LogCat
04-24 03:40:53.821: E/AndroidRuntime(1701): FATAL EXCEPTION: main
04-24 03:40:53.821: E/AndroidRuntime(1701): Process: com.test.ribbit, PID: 1701
04-24 03:40:53.821: E/AndroidRuntime(1701): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.test.ribbit/com.test.ribbit.MainActivity}: java.lang.NullPointerException
04-24 03:40:53.821: E/AndroidRuntime(1701): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
04-24 03:40:53.821: E/AndroidRuntime(1701): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
04-24 03:40:53.821: E/AndroidRuntime(1701): at android.app.ActivityThread.access$800(ActivityThread.java:135)
04-24 03:40:53.821: E/AndroidRuntime(1701): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
04-24 03:40:53.821: E/AndroidRuntime(1701): at android.os.Handler.dispatchMessage(Handler.java:102)
04-24 03:40:53.821: E/AndroidRuntime(1701): at android.os.Looper.loop(Looper.java:136)
04-24 03:40:53.821: E/AndroidRuntime(1701): at android.app.ActivityThread.main(ActivityThread.java:5017)
04-24 03:40:53.821: E/AndroidRuntime(1701): at java.lang.reflect.Method.invokeNative(Native Method)
04-24 03:40:53.821: E/AndroidRuntime(1701): at java.lang.reflect.Method.invoke(Method.java:515)
04-24 03:40:53.821: E/AndroidRuntime(1701): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-24 03:40:53.821: E/AndroidRuntime(1701): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-24 03:40:53.821: E/AndroidRuntime(1701): at dalvik.system.NativeStart.main(Native Method)
04-24 03:40:53.821: E/AndroidRuntime(1701): Caused by: java.lang.NullPointerException
04-24 03:40:53.821: E/AndroidRuntime(1701): at com.test.ribbit.MainActivity.onCreate(MainActivity.java:75)
04-24 03:40:53.821: E/AndroidRuntime(1701): at android.app.Activity.performCreate(Activity.java:5231)
04-24 03:40:53.821: E/AndroidRuntime(1701): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
04-24 03:40:53.821: E/AndroidRuntime(1701): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
04-24 03:40:53.821: E/AndroidRuntime(1701): ... 11 more
Ben Jakuben
Treehouse TeacherOkay, the first error is still related to regular vs support Fragments. I'm very sorry for this trouble - it's a real pain.
A new error message appear in the MainActivity.java "The constructor SectionsPagerAdapter(MainActivity, FragmentManager) is undefined" (line 57)
Change line 57 to this:
mSectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());
Then, your other error is at line 75 if you look at the NullPointerException in the logcat message. That line appears to be:
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
which is probably related to the first error. Fix that line and let's see what happens. :)
axel treza
3,702 PointsThanks a lot for your reply,
After following your instructions I get the following error message on line 57 : "The method getSupportFragmentManager() is undefined for the type MainActivity" And the emulator cannot launch the app because of this error.
Ben Jakuben
Treehouse TeacherAh, I missed another difference. You need to extend FragmentActivity
instead of Activity
and include this import statement:
import android.support.v4.app.FragmentActivity;
Ross Kistinger
3,609 PointsThanks for the help Ben, I was having the same issues. Some Teacher Notes on the Modifying Fragments video would be helpful.
Gilad Solter
2,986 PointsI did the same as Jeremy Broutin only I had to delete: import android.app.Fragment; from my mainActivity class
J Smillie
39,714 PointsCan someone help me with what is going wrong for me? I'm getting errors all over my code in Android Studio. The first error is that an import isn't there... but when I check above the import is there??
SectionsPagerAdapter doesn't seem to be recognised and the ActionBar is behaving strangely.
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import com.parse.ParseAnalytics;
import com.parse.ParseUser;
import java.util.HashMap;
import java.util.Map;
public class MyActivity extends FragmentActivity{
public static final String TAG = MyActivity.class.getSimpleName();
/**
* 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_my);
Map<String, String> dimensions = new HashMap<String, String>();
// What type of news is this?
dimensions.put("category", "politics");
// Is it a weekday or the weekend?
dimensions.put("dayType", "weekday");
// Send the dimensions to Parse along with the 'read' event
ParseAnalytics.trackEvent("read", dimensions);
ParseUser currentUser = ParseUser.getCurrentUser();
if (currentUser == null) {
navigateToLogin();
}
else {
Log.i(TAG, currentUser.getUsername());
}
// 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 activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(this, 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));
}
}
private void navigateToLogin() {
Intent intent = new Intent(this, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.my, 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 itemId = item.getItemId();
if (itemId == R.id.action_logout) {
ParseUser.logOut();
navigateToLogin();
}
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 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_my, container, false);
return rootView;
}
}
}
ahmet yuva
17,595 Pointsi cant see any text in my inbox fragment or in friends fragment, i can see section names inbox and friends but when i click them then there is empty page and this is my code , please help me asap its emergecny
this is my MainActiviy.java
package com.ahmetyuva.ribbit;
import java.util.Locale;
import android.support.v7.app.ActionBarActivity; import android.support.v7.app.ActionBar; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.app.FragmentPagerAdapter; import android.os.Bundle; import android.support.v4.view.ViewPager; import android.view.Gravity; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.Locale;
import android.content.Intent; import android.support.v7.app.ActionBarActivity; import android.support.v7.app.ActionBar; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.content.Context;
import android.os.Bundle; import android.support.v4.view.ViewPager; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.TextView;
import com.parse.Parse; import com.parse.ParseAnalytics; import com.parse.ParseException; import com.parse.ParseObject; import com.parse.ParseUser; import com.parse.SignUpCallback;
public class MainActivity extends ActionBarActivity implements ActionBar.TabListener {
public static final String TAG = MainActivity.class.getSimpleName();
/**
* 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_main);
ParseUser currentUser = ParseUser.getCurrentUser();
if(currentUser == null) {
navigateToLogin();
}
else{
Log.i(TAG, currentUser.getUsername());
}
// 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));
}
}
private void navigateToLogin() {
Intent intent = new Intent(this, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
@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_main, 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_logout) {
ParseUser.logOut();
navigateToLogin();
}
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 2;
}
@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);
}
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() {
}
}
}
this is InboxFragment.java
package com.ahmetyuva.ribbit;
import android.os.Bundle; import android.support.v4.app.ListFragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup;
/**
-
Created by ahmetyuva on 06/04/15. */ public class InboxFragment extends ListFragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_inbox, container, false);
return rootView;
}
}
and this is SectionsPagerAdapter.java
package com.ahmetyuva.ribbit;
/**
- Created by ahmetyuva on 06/04/15. */
import android.content.Context; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter;
import java.util.Locale;
/**
- A {@link android.support.v4.app.FragmentPagerAdapter} that returns a fragment corresponding to
-
one of the sections/tabs/pages. */ public class SectionsPagerAdapter extends FragmentPagerAdapter {
protected Context mContext;
public SectionsPagerAdapter(Context context, FragmentManager fm) { super(fm); mContext = context; }
@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).
switch (position){ case 0: return new InboxFragment(); case 1: return new FriendsFragment(); } return null;
}
@Override public int getCount() {
return 2;
}
@Override public CharSequence getPageTitle(int position) { Locale l = Locale.getDefault(); switch (position) { case 0: return mContext.getString(R.string.title_section1).toUpperCase(l); case 1: return mContext.getString(R.string.title_section2).toUpperCase(l);
} return null;
} }
Nicolas Hampton
44,638 PointsIf everyone would like to see working undeprecated code for this lesson that still uses the tab interface, see the question "This Is The Droid You Are Looking For" in the forum for source code and explanation.
Ankit B
4,180 PointsAnkit B
4,180 PointsI was having similar problem. Thanks for posting it! :D