I have implemented navigation drawer in my android app. but now I want to be able to change the layout using fragments when the user clicks any list item in the navigation bar.
Here is what I have got so far:
XML
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:background="#000000"
android:layout_height="match_parent" >
</FrameLayout>
<ListView android:id="#+id/left_drawer"
android:layout_width="220dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#111"/>
</android.support.v4.widget.DrawerLayout>
Java File
public class MainActivity extends Activity {
final String[] data ={"one","two","three"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data);
final DrawerLayout drawer = (DrawerLayout)findViewById(R.id.drawer_layout);
final ListView navList = (ListView) findViewById(R.id.left_drawer);
navList.setAdapter(adapter);
navList.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, final int pos,long id){
drawer.setDrawerListener( new DrawerLayout.SimpleDrawerListener(){
#Override
public void onDrawerClosed(View drawerView){
super.onDrawerClosed(drawerView);
}
});
drawer.closeDrawer(navList);
}
});
}
}
Using the above code, I implemented navigation drawer in my app and I see "one", "two" and "Three" list items in the navigation drawer but nothing happens when I click on them except the drawer closes.
So, my question is :
How do I add the fragment functionality to the above given code?
I am beginner. Thanks in advance!
On click have
selectItem(pos);
Then
public void selectItem(int position)
{
switch(position)
{
case 0:
// fragment1
// use fragment transaction and add the fragment to the container
FragmentManager fragmentManager = getFragmentManager()
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment1 fragment = new Fragment1();
fragmentTransaction.add(R.id.content_frame, fragment);
fragmentTransaction.commit();
break;
case 1:
// fragment2
break;
case 2:
// fragment2
break;
}
}
use This:
public class MenuFragmentActivity extends FragmentActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.base_layout);
addFragments(new Sample(), false, false,
AndyConstants.CONTENT_PAGE);
}
public void addFragments(Fragment fragment, boolean animate,
boolean addToBackStack, String tag) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction ft = manager.beginTransaction();
if (animate) {
ft.setCustomAnimations(R.anim.fragment_from_right,
R.anim.fragment_from_left, R.anim.fragment_from_right,
R.anim.fragment_from_left);
}
if (addToBackStack) {
ft.addToBackStack(tag);
}
ft.replace(R.id.content_frame, fragment);
ft.commit();
}
}
For Fragment:
public class Sample extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.page, container, false);
return view;
}
}
After generate a Navigation Drawer Activity by File->New->Activity->Navigation Drawer Activity, here are 3 steps
First, go to app_bar_main.xml then
replace
<include layout="#layout/content_main"/>
by
<FrameLayout
android:id="#+id/frame_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
/>
Second, go to MainActivity -> onNavigationItemSelected then modify it like
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
Fragment fragment = null;
if (id == R.id.nav_camera) {
fragment = CameraFragment.newInstance();
} else if (id == R.id.nav_gallery) {
fragment = GalleryFragment.newInstance();
} else if (id == R.id.nav_slideshow) {
fragment = SlideShowFragment.newInstance();
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame_content, fragment).commit();
setTitle(item.getTitle());
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
Finally, create Fragment class, example a Fragment
public class CameraFragment extends Fragment{
public static CameraFragment newInstance() {
Bundle args = new Bundle();
CameraFragment fragment = new CameraFragment();
fragment.setArguments(args);
return fragment;
}
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_camera, null, false);
return rootView;
}
}
Demo project
Related
Hi I am new to Android so if my question seems redundant, please bear with me as I was unable to find a proper answer anywhere. I have a main activity with 4 tabs on the bottom navigation bar and three fragments to populate these tabs. Now when I start a child of any of these fragments, the child is not displayed with the navigation bar. How do i achieve this?
MainActivity.class main function
BottomNavigationView bottomNavigationView = (BottomNavigationView)
findViewById(R.id.navigation);
// BottomNavigationViewHelper.disableShiftMode(bottomNavigationView);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.action_item1:
selectedFragment = TabOneFragment.newInstance();
break;
case R.id.action_item2:
selectedFragment = TabTwoFragment.newInstance();
break;
case R.id.action_item3:
selectedFragment = TabThreeFragment.newInstance();
break;
}
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace( R.id.frame_layout,selectedFragment);
transaction.commit();
return true;
}
});
//Manually displaying the first fragment - one time only
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_layout, TabOneFragment.newInstance());
transaction.commit();
TabActivity
public class TabOneFragment extends Fragment {
ArrayList<SettingsClass> data;
private Button send;
ListView listView;
public static TabOneFragment newInstance() {
TabOneFragment fragment = new TabOneFragment();
return fragment;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
#Override
public void onViewStateRestored(#Nullable Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_tab_one_fragment, container, false);
return v;
}
#Override
public void onViewCreated(View view, #Nullable final Bundle savedInstanceState) {
data = new ArrayList<>();
data.add(new SettingsClass("Option1", R.drawable.o1));
data.add(new SettingsClass("Option2", R.drawable.o2));
listView = view.findViewById(R.id.listView);
MyAdapter adapter = new MyAdapter(getActivity().getApplicationContext(), data);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 0: {
Intent intent = new Intent(getActivity().getApplicationContext(),ChildActivity.class);
startActivity(intent);
break;
}
case 1: {
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + "NO_CONTACT"));
startActivity(intent);
break;
}
}
}
});
The ChildActivity is not created with the navigation bottom tab. Can anybody guide me??
layout for tab one:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
>
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listView">
</ListView>
</RelativeLayout>
I have a MainActivIty and it supports two fragments i.e Home and Profile.Home has a TabLayout which in turn has three fragments Trending,Followed and Nearby.
So the issue is when Home is first time loaded it shows the content of the Tab fragments and slider of tab layout moves properly but when I got to profile and then to home then the tab layout fragments do not load and while swiping left to right slider does not move smoothly.Here is the code.
public class MainActivity extends AppCompatActivity {
ImageButton home_btn,myProfile_btn;
FragmentManager fragmentManager;
FragmentTransaction fragmentTransaction;
TextView txt_action_bar;
Home home;
ProfileFragment profile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
home_btn=(ImageButton)findViewById(R.id.home_btn) ;
discover_btn=(ImageButton)findViewById(R.id.discover_btn) ;
myProfile_btn=(ImageButton)findViewById(R.id.profile_btn) ;
notification_btn=(ImageButton)findViewById(R.id.notification_btn) ;
plus_btn=(ImageButton)findViewById(R.id.btn_plus) ;
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
txt_action_bar = (TextView)findViewById(R.id.toolbar_title);
displayMetrics = getResources().getDisplayMetrics();
Typeface custom_font = Typeface.createFromAsset(getAssets(),"fonts/NoteworthyLight.ttf");
txt_action_bar.setTypeface(custom_font);
setSupportActionBar(toolbar);
fragmentManager = getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
home = new Home();
profile = new ProfileFragment();
fragmentTransaction.add(R.id.main_fragment_container,home,"home");
fragmentTransaction.commit();
}
public void onClickHome(View view)
{
fragmentManager = getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.main_fragment_container,home,"home");
fragmentTransaction.commit();
}
public void onClickMyProfile(View view)
{
fragmentManager = getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.main_fragment_container,profile,"profile");
fragmentTransaction.commit();
}
}
Home.java
public class Home extends Fragment {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
public Home() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_home, container, false);
mSectionsPagerAdapter = new SectionsPagerAdapter(getFragmentManager());
mViewPager = (ViewPager) view.findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) view.findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
return view;
}
FollowedFragment.java
public class FollowedFragment extends Fragment {
public FollowedFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.feeds_list, container, false);
new DownloadFollowedFeeds().execute();
return rootView;
}
fragment_home.xml
<LinearLayout android:layout_below="#+id/header"
android:layout_above="#+id/footer"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_gravity="center_vertical"
android:orientation="vertical"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
style="#style/TabNameStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/medium_turquoise"
app:tabGravity="fill"
app:tabMode="fixed" />
<android.support.v4.view.ViewPager
android:id="#+id/container"
android:layout_width="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:layout_height="fill_parent"/>
SectionPagerAdapter.java
public class SectionsPagerAdapter extends FragmentPagerAdapter {
private String tabTitles[] = new String[] { "Trending", "Followed","Nearby" };
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).
Log.i("tag","number"+String.valueOf(position));
if(position==0) return new TrendingFragment();
else if(position==1) return new FollowedFragment();
else return new NearbyFragment();
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
return tabTitles[position];
}
}
As answered here:
When you are creating the view adapter in Home.java:
instead of
mSectionsPagerAdapter = new SectionsPagerAdapter(getFragmentManager());
you should do,
mSectionsPagerAdapter = new SectionsPagerAdapter(getChildFragmentManager());
i want to redirect activity to fragment when clicking button but it gives me error.
here is my activity class
public class EventDetailsNotif extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.eventdetails);
ImageButton imgmenu = (ImageButton) findViewById(R.id.imgmenu);
imgmenu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loadFragmentObj = new LoadFragment(getFragmentManager());
loadFragmentObj.initializeFragment(new ManagemntPageFragment());
}
});
}
}
and my load fragment class is here.
public class LoadFragment {
FragmentManager fragmentManager;
FragmentManager fragmentManager1;
public LoadFragment(FragmentManager fragmentManager2) {
this.fragmentManager = fragmentManager2;
}
public void initializeFragment(Fragment resultFragment) {
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
fragmentTransaction.replace(R.id.content, resultFragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
}
and my content.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent" />
and my fragment class.
public class ManagemntPageFragment extends Fragment {
ImageView footervie;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = (RelativeLayout) inflater.inflate(R.layout.managmntpg,
container, false);
footervie = (ImageView) view.findViewById(R.id.footervie);
advtimagepath = Utility.getSharedKey("advertiseFooter_image",
getActivity());
if (!TextUtils.isEmpty(advtimagepath)) {
if (advtimagepath.endsWith(".jpeg")
|| advtimagepath.endsWith(".jpg")
|| advtimagepath.endsWith(".gif")
|| advtimagepath.endsWith(".png")) {
imageLoader = new ImageLoader(getActivity());
imageLoader.DisplayImage(advtimagepath, footervie);
} else {
}
}
return view ;
}
}
please reply if have solution
are you sure you have below code
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent" />
in eventdetails layout file because you set content menu in activity to this layout
setContentView(R.layout.eventdetails);
and if you don't use support library for fragment you will have compatibility with older android version!
I am stuck in a problem with the view pager.The view pager works fine initially,the adapter calls the getItem(int pos) method and the pages get setup properly.
Now the problem arises when i try to replace a page in the view pager.The pagefragment is getting replaced but showing a blank screen.
I am not getting what to do next.
Tried calling `notifyDatasetChanged() but still no effect.
Heres the code`
public class BaseActivity extends FragmentActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mActions;
private static final int NUM_PAGES = 2;
private ViewPager mPager;
private PagerAdapter mPagerAdapter;
private FragmentManager fragmentManager;
private FragmentTransaction fragmentTransaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.common_layout);
// Instantiate a ViewPager and a PagerAdapter.
fragmentManager = getSupportFragmentManager();
mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);
mTitle = mDrawerTitle = getTitle();
mActions = getResources().getStringArray(R.array.actions);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
// set up the drawer's list view with items and pclick listener
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mActions));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
}
// The click listener for ListView in the navigation drawer
private class DrawerItemClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
selectItem(position);
}
}
private void selectItem(int position) {
switch (position) {
case 0:
replaceFragment(new DashFragment());
break;
case 1:
replaceFragment(new SearchFragment());
break;
case 2:
replaceFragment(new UploadFragment());
break;
default:
replaceFragment(new DashFragment());
break;
}
mDrawerList.setItemChecked(position, true);
setTitle(mActions[position]);
Toast.makeText(this, "Title is=" + getTitle(), 1).show();
mDrawerLayout.closeDrawer(mDrawerList);
}
private void replaceFragment(Fragment newContentFragment) {
// TODO Auto-generated method stub
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
fragmentTransaction.replace(R.id.pager, newContentFragment);
fragmentTransaction.addToBackStack(String.valueOf(newContentFragment
.getId()));
fragmentTransaction.commit();
}
#Override
public void onBackPressed() {
if (mPager.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.
mPager.setCurrentItem(mPager.getCurrentItem() - 1);
}
}
private class ScreenSlidePagerAdapter extends FragmentPagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new DashFragment();
case 1:
return new SearchFragment();
default:
return new DashFragment();
}
}
#Override
public int getCount() {
return NUM_PAGES;
}
}
}
Here's my common_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:focusable="true"
android:focusableInTouchMode="true" />
<ListView
android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="left"
android:background="#111"
android:choiceMode="singleChoice" />
</android.support.v4.widget.DrawerLayout>
Here are the solutions of your problem .These have the good explanation as well ..
first
second
keep it DRY :)
Let me know if you need further explanation.
In my application, I have used the SherlockNavigationDrawer. By default, the navigationDrawer has 3 menu to opens 3 fragments. I have modified one of the following fragment. But when click for the second time on the menu of my fragment, screen not display anything! The first time, no problem; But the second time, a blank page is displayed.
In this case, if click on the default fragment menu in NavigationDrawer and then click on my fragment on the screen comes back on, but if click on my fragment menu again, screen show a blank page!
Also i have shown in my fragment a list of items, that by click on each item replace new fragment that show details of the specific item. but detail fragment is a display that is empty!!!
Friends! Where is the problem?
MainActivity Code:
public class ActivityMain extends SherlockFragmentActivity {
// Declare Variables
DrawerLayout mDrawerLayout;
ListView mDrawerList;
ActionBarDrawerToggle mDrawerToggle;
MenuListAdapter mMenuAdapter;
String[] title;
String[] subtitle;
int[] icon;
Fragment fragment1 = new Fragment1();
Fragment fragment2 = new Fragment2();
Fragment fragment_categorylist = new Fragment_CategoryList();
private CharSequence mDrawerTitle;
private CharSequence mTitle;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from drawer_main.xml
setContentView(R.layout.drawer_main);
// Get the Title
mTitle = mDrawerTitle = getTitle();
// Generate title
title = new String[] { getString(R.string.TitleFragment1),
getString(R.string.TitleFragment2),
getString(R.string.TitleFragment3) };
// Generate subtitle
subtitle = new String[] { getString(R.string.SubtitleFragment1),
getString(R.string.SubtitleFragment2),
getString(R.string.SubtitleFragment3) };
// Generate icon
icon = new int[] { R.drawable.action_about, R.drawable.action_settings,
R.drawable.collections_cloud };
// Locate DrawerLayout in drawer_main.xml
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
// Locate ListView in drawer_main.xml
mDrawerList = (ListView) findViewById(R.id.listview_drawer);
// Set a custom shadow that overlays the main content when the drawer
// opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
ActivitySwipeDetector swipe = new ActivitySwipeDetector(this);
DrawerLayout swipe_layout = (DrawerLayout) findViewById(R.id.drawer_layout);
swipe_layout.setOnTouchListener(swipe);
//LinearLayout swipe_layout2 = (LinearLayout) findViewById(R.id.fragment_pager_layout);
//swipe_layout2.setOnTouchListener(swipe);
// Pass string arrays to MenuListAdapter
mMenuAdapter = new MenuListAdapter(ActivityMain.this, title, subtitle,
icon);
// Set the MenuListAdapter to the ListView
mDrawerList.setAdapter(mMenuAdapter);
// Capture listview menu item click
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// Enable ActionBar app icon to behave as action to toggle nav drawer
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.drawer_open,
R.string.drawer_close) {
public void onDrawerClosed(View view) {
// TODO Auto-generated method stub
super.onDrawerClosed(view);
}
public void onDrawerOpened(View drawerView) {
// TODO Auto-generated method stub
// Set the title on the action when drawer open
getSupportActionBar().setTitle(mDrawerTitle);
super.onDrawerOpened(drawerView);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
mDrawerLayout.closeDrawer(mDrawerList);
} else {
mDrawerLayout.openDrawer(mDrawerList);
}
}
return super.onOptionsItemSelected(item);
}
// ListView click listener in the navigation drawer
private class DrawerItemClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
selectItem(position);
}
}
private void selectItem(int position) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
// Locate Position
switch (position) {
case 0:
ft.replace(R.id.content_frame, fragment1);
break;
case 1:
ft.replace(R.id.content_frame, fragment2);
break;
case 2:
ft.replace(R.id.content_frame, fragment_categorylist);
break;
}
ft.commit();
mDrawerList.setItemChecked(position, true);
// Get the title followed by the position
setTitle(title[position]);
// Close drawer
mDrawerLayout.closeDrawer(mDrawerList);
}
Default Fragment Code:
public class Fragment3 extends SherlockFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment3, container, false);
return rootView;
}
}
My Fragment (Modified Fragment) :
public class Fragment_CategoryList extends SherlockFragment {
static final int NUM_ITEMS = 1;
MyAdapter mAdapter;
ViewPager mPager;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_pager, container,
false);
mAdapter = new MyAdapter(getSherlockActivity().getSupportFragmentManager());
mPager = (ViewPager) rootView.findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
// Watch for button clicks.
Button button = (Button) rootView.findViewById(R.id.goto_first);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mPager.setCurrentItem(0);
}
});
button = (Button) rootView.findViewById(R.id.goto_last);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mPager.setCurrentItem(NUM_ITEMS - 1);
}
});
return rootView;
}
// ////////////////////////////////////////////////////////////////////////
public static class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return NUM_ITEMS;
}
#Override
public Fragment getItem(int position) {
return ArrayListFragment.newInstance(position);
}
}
public static class ArrayListFragment extends SherlockListFragment {
int mNum;
/**
* Create a new instance of CountingFragment, providing "num" as an
* argument.
*/
static ArrayListFragment newInstance(int num) {
ArrayListFragment f = new ArrayListFragment();
// Supply num input as an argument.
Bundle args = new Bundle();
args.putInt("num", num);
f.setArguments(args);
return f;
}
/**
* When creating, retrieve this instance's number from its arguments.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mNum = getArguments() != null ? getArguments().getInt("num") : 1;
}
/**
* The Fragment's UI is just a simple text view showing its instance
* number.
*/
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_pager_list, container,
false);
View tv = v.findViewById(R.id.text);
((TextView) tv).setText("Fragment #" + mNum);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// setListAdapter(new ArrayAdapter<String>(getActivity(),
// android.R.layout.simple_list_item_1, Cheeses.sCheeseStrings));
DBAdapter db = new DBAdapter(getActivity());
// Create an array to specify the fields we want to display in the
// list (only TITLE)
String[] from = new String[] { "title", "_id" };
// and an array of the fields we want to bind those fields to (in
// this case just text1)
int[] to = new int[] { R.id.entry1, R.id.entry2 };
ArrayList<HashMap<String, String>> categoryList = db.getAll();
if (categoryList.size() != 0) {
ListAdapter adapter = new SimpleAdapter(getActivity(),
categoryList,
R.layout.fragment_pager_list_entry, from, to);
setListAdapter(adapter);
}
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
final FragmentTransaction ft = getSherlockActivity().getSupportFragmentManager().beginTransaction();
Fragment myFragment = new Fragment_QA();
int idplus = (int)id + 1;
Bundle args = new Bundle();
args.putLong("cid", idplus);
//myFragment.setArguments(args);
ft.replace(((ViewGroup)(getView().getParent())).getId(), myFragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(null);
ft.commit();
}
}
}
Main Activity UI:
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ListView
android:id="#+id/listview_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#111"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp" />
My Fragment UI (Fragment_CategoryList):
<LinearLayout
android:orientation="vertical" android:padding="4dip"
android:gravity="center_horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1">
</android.support.v4.view.ViewPager>
<LinearLayout android:orientation="horizontal"
android:gravity="center" android:measureWithLargestChild="true"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:layout_weight="0">
<Button android:id="#+id/goto_first"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="FIRST">
</Button>
<Button android:id="#+id/goto_last"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="LAST">
</Button>
</LinearLayout>
I don't know if this question is still available but for someone could be a helpful answer.
That's what you should do :
change from
android.support.v4.app.FragmentPagerAdapter to android.support.v4.app.FragmentStatePagerAdapter
try to change getSupportFragmentManager to getChildFragmentManager