Viewpager and fragment on android studio - android

android developers please help, I Have viewpager with fragments, when i slide in the pages and reached the last page and then when i return to the first page again the fragment of the first page loads its default display.Please help..here is my code in MainActivity
public class MainActivity extends AppCompatActivity {
private ActionBarDrawerToggle actionBarDrawerToggle;
private DrawerLayout drawerLayout;
private ListView navList;
private FragmentManager fragmentManager;
private FragmentTransaction fragmentTransaction;
private ActionBar actionBar;
private ViewPager pager;
private Menu menu;
private float lastTranslate = 0.0f;
private FrameLayout mainframe, galleryframe;
private Frag_Gallery fragGallery;
private Frag_Create fragCreate;
private Frag_Account fragAccount;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pager = (ViewPager) findViewById(R.id.viewPager);
mainframe = (FrameLayout) findViewById(R.id.fragmentholder);
galleryframe = (FrameLayout) findViewById(R.id.galleryholder);
pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
ColorDrawable colorDrawable = new ColorDrawable(Color.parseColor("#0b115e"));
Main_Menu Menu_data[] = new Main_Menu[]
{
new Main_Menu(R.mipmap.gallery_icon, "Gallery"),
new Main_Menu(R.mipmap.create_icon, "Create Your Own"),
new Main_Menu(R.mipmap.account_icon, "My Account"),
new Main_Menu(R.mipmap.contact_icon, "Contact Us")
};
MainMenuAdapter adapter = new MainMenuAdapter(this,
R.layout.listviewmain_item_row, Menu_data);
drawerLayout = (DrawerLayout) findViewById(R.id.drawerlayout);
navList = (ListView) findViewById(R.id.navList);
View header = (View) getLayoutInflater().inflate(R.layout.listviewmain_header_row, null);
navList.addHeaderView(header);
navList.setAdapter(adapter);
navList.setDivider(null);
navList.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
navList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
loadSelection(position);
drawerLayout.closeDrawer(navList);
}
});
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.opendrawer, R.string.closedrawer);
drawerLayout.setDrawerListener(actionBarDrawerToggle);
actionBar = getSupportActionBar();
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setBackgroundDrawable(colorDrawable);
actionBar.setTitle("");
fragmentManager = getSupportFragmentManager();
loadSelection(0);
pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int pos) {
switch (pos) {
case 0:
menu.getItem(0).setIcon(R.mipmap.gallery_icon);
menu.getItem(1).setIcon(R.mipmap.create_icon_off);
menu.getItem(2).setIcon(R.mipmap.account_icon_off);
break;
case 1:
menu.getItem(0).setIcon(R.mipmap.gallery_icon_off);
menu.getItem(1).setIcon(R.mipmap.create_icon);
menu.getItem(2).setIcon(R.mipmap.account_icon_off);
break;
case 2:
menu.getItem(0).setIcon(R.mipmap.gallery_icon_off);
menu.getItem(1).setIcon(R.mipmap.create_icon_off);
menu.getItem(2).setIcon(R.mipmap.account_icon);
break;
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
this.menu = menu;
getMenuInflater().inflate(R.menu.menu_main, menu);
menu.getItem(0).setIcon(R.mipmap.gallery_icon);
menu.getItem(1).setIcon(R.mipmap.create_icon_off);
menu.getItem(2).setIcon(R.mipmap.account_icon_off);
return true;
}
private void loadSelection(int i) {
switch (i) {
case 1:
actionBar.setTitle("Gallery");
pager.setCurrentItem(0, true);
break;
case 2:
actionBar.setTitle("Design");
pager.setCurrentItem(1, true);
break;
case 3:
actionBar.setTitle("Account");
pager.setCurrentItem(2, true);
break;
case 4:
actionBar.setTitle("Contact us");
break;
default:
actionBar.setTitle("");
break;
}
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
actionBarDrawerToggle.syncState();
}
#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 == android.R.id.home) {
if (drawerLayout.isDrawerOpen(navList)) {
drawerLayout.closeDrawer(navList);
} else {
drawerLayout.openDrawer(navList);
}
}
return super.onOptionsItemSelected(item);
}
private class MyPagerAdapter extends FragmentPagerAdapter {
private Fragment fragment;
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int pos) {
fragment = new Fragment();
switch (pos) {
case 0:
fragment = new Frag_Gallery();
break;
case 1:
fragment = new Frag_Create();
break;
case 2:
fragment = new Frag_Account();
default:
break;
}
return fragment;
}
#Override
public int getCount() {
return 3;
}
}
}

use
pager.setOffscreenPageLimit(X);
where X is the count of the pages you want to save so the ViewPager wont rebuild them.

Related

View Pager addOnPageChangeListener doesn't work with Fragment Pager Adapter

I'm having trouble implementing "addOnPageChangeListener" for my viewPager. I'm essentially implementing THIS; its a slider view with fragments, I'm doing the same with child fragments.
When I add the viewListener to my ViewPager, my app crashes. It works fine without the addOnPageListener. I want to do this so I can put some title animations for my actionbar and maybe some background effects.
This is what it looks like:
View Pager App Screenshot.
Any help or suggestions would be appreciated, thanks!
LogCat:
https://pastebin.com/xqsBQ46h
JavaCode:
package com.example.varungovind.tm_alpha000;
import android.os.Bundle;
...
public class HomeFragment extends Fragment implements NavigationView.OnNavigationItemSelectedListener{
private DrawerLayout mDrawer;
private ViewPager mViewPager;
private SamplePagerAdapter mPagerAdapter;
private Toolbar mToolBar;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
//sets the system bar transparent
Objects.requireNonNull(getActivity()).getWindow().getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_VISIBLE);
//ToolBar and Navigation Drawer
mToolBar = view.findViewById(R.id.fragment_toolbar);
((AppCompatActivity)getActivity()).setSupportActionBar(mToolBar);
mDrawer = view.findViewById(R.id.nav_drawer_layout);
NavigationView navigationView = view.findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(getActivity(), mDrawer, mToolBar, R.string.nav_drawer_open, R.string.nav_drawer_close);
mDrawer.addDrawerListener(toggle);
toggle.syncState();
//Setting toolbar title
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle("");
final Animation fade_in = AnimationUtils.loadAnimation(getContext(), R.anim.fade_in);
final Animation fade_out = AnimationUtils.loadAnimation(getContext(), R.anim.fade_out);
final TextView toolbar_title = view.findViewById(R.id.toolbar_title);
//This line of code causes the error
mViewPager.addOnPageChangeListener(viewListener);
//SliderViewPager
mViewPager = view.findViewById(R.id.fragment_home_view_pager);
mPagerAdapter = new SamplePagerAdapter(getChildFragmentManager());
mViewPager.setAdapter(mPagerAdapter);
mViewPager.setPageTransformer(false, new ZoomOutPageTransformer());
return view;
}
ViewPager.OnPageChangeListener viewListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
#Override
public void onPageSelected(int position) {}
#Override
public void onPageScrollStateChanged(int state) {}
};
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.nav_about:
break;
case R.id.nav_donate:
break;
case R.id.nav_done:
mViewPager.setCurrentItem(1, true);
break;
case R.id.nav_upcoming:
mViewPager.setCurrentItem(0, true);
break;
case R.id.nav_feedback:
break;
case R.id.nav_drawer_new_list:
break;
case R.id.nav_settings:
break;
}
mDrawer.closeDrawer(GravityCompat.START);
return true;
}
private class SamplePagerAdapter extends FragmentPagerAdapter {
public SamplePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public CFragment getItem(int position) {
/** Show a Fragment based on the position of the current screen */
if (position == 0) {
return new Upcoming_ChildFragment();
} else
return new Done_ChildFragment();
}
#Override
public int getCount() {
// Show 2 total pages.
return 2;
}
}
}
Try to add the listerner mViewPager.addOnPageChangeListener(viewListener);
after setting the adpater.

android studio change title using fragment

i have a problem with changing my title. i can change the title using fragment but each time i click or change to another fragment the title is didnt change to the correct title. here is my code:
This is my main tabactivity
public class TabActivity extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tab);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// 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.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#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_tab, 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);
}
/**
* 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:
profile_menu tab1 = new profile_menu();
return tab1;
case 1:
group_menu tab2 = new group_menu();
return tab2;
case 2:
world_menu tab3 = new world_menu();
return tab3;
case 3:
prize_menu tab4 = new prize_menu();
return tab4;
default:
return null;
}
}
#Override
public int getCount() {
// Show 3 total pages.
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Profile ";
case 1:
return "Group ";
case 2:
return "World ";
case 3:
return "Prize";
}
return null;
}
}
public void setActionBarTitle(String title){
getSupportActionBar().setTitle(title);
}
}
and this is my fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.prize_menu, container, false);
getActivity().setTitle("Prize");
return rootView;
}
I assume that you want to change the title when tab change?
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
switch (position) {
case 0:
getSupportActionBar().setTitle("Profile ");
break;
case 1:
getSupportActionBar().setTitle("Group");
break;
case 2:
getSupportActionBar().setTitle("World");
break;
case 3:
getSupportActionBar().setTitle("Prize");
break;
default:
break;
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
if (getActivity().getActionBar() != null) {
getActivity().getActionBar().setTitle("YourTitle");
}
Use this line in onViewCreated() of each fragment will solve your problem
call getActivity().setTitle("Prize"); it in onResume of each fragment
In Fragment
Set your title in simple way. Add this method in your common class.
Add your title with back arrow in action bar.
public void setPageTitle(String title) {
((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayShowCustomEnabled(false);
((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle(Html.fromHtml("<font color='#ffffff'>"+title+ "</font>"));
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstantState){
view = inflater.inflate(R.layout.fragment_name,container,false);
setPageTitle("title");
return view;
}
If you want title alone, use this line alone in your fragment onCreateView(). But this code does not handle back arrow.
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle("Title");
Quick way to do:
Declare your ToolBar as static and access from the fragment:
MainActivity:
public static Toolbar mToolbar;
in your fragment:
mToolbar.setTitle("your title here");
You set the Fragment title in the mobile_navigation.xml file in res -> navigation.
Use the android:label=""

Android FragmentPagerAdapter detect if user has visited a specific tab

I have multiple tabs using FragmentPagerAdapter but the ViewPager creates a page before and after my current tab and the OnCreate() method gets called even when I'm not on that tab. It becomes really difficult to run a specific operation on a specific tab rather than executing before visiting the tab. Is there anyway so that I can detect if the user has visited the particular tab from the tab itself?
public class MainActivity extends ActionBarActivity implements ViewPager.OnPageChangeListener {
public static final int TAB_PROFILE = 0;
public static final int TAB_JOBS = 1;
public static final int TAB_GPS = 2;
public static final int TAB_COMMENTS = 3;
public static final int TAB_OTHERS = 4;
Toolbar toolbar;
private ViewPager mPager;
private SlidingTabLayout mTabs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
NavigationDrawerFragment drawerFragment = (NavigationDrawerFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), toolbar);
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
mPager.setOnPageChangeListener(this);
mTabs = (SlidingTabLayout) findViewById(R.id.tabs);
mTabs.setCustomTabView(R.layout.custom_tab_item, R.id.tabText);
mTabs.setDistributeEvenly(true);
mTabs.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
mTabs.setSelectedIndicatorColors(getResources().getColor(R.color.colorAccent));
mTabs.setViewPager(mPager);
}
#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_settings) {
return true;
}
if (id == R.id.action_search) {
startActivity(new Intent(this, subActivity.class));
}
return super.onOptionsItemSelected(item);
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
Log.d("CURRENT_TAB", "" + position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
class MyPagerAdapter extends FragmentPagerAdapter {
//String[] tabsTitle = getResources().getStringArray(R.array.tabs);
int tabIcons[] = {R.drawable.ic_tab_home,
R.drawable.ic_tab_job,
R.drawable.ic_tab_map,
R.drawable.ic_tab_comments,
R.drawable.ic_tab_others};
public MyPagerAdapter(FragmentManager fm) {
super(fm);
//tabsTitle = getResources().getStringArray(R.array.tabs);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
Logs.logs("getItem called for " + position);
switch (position) {
case TAB_PROFILE:
fragment = FragmentProfile.newInstance("" + position, "true");
break;
case TAB_JOBS:
fragment = FragmentJobs.newInstance("" + position, "true");
break;
case TAB_GPS:
fragment = FragmentGPS.newInstance("" + position, "true");
break;
case TAB_COMMENTS:
fragment = FragmentComments.newInstance("" + position, "true");
break;
case TAB_OTHERS:
fragment = FragmentOthers.newInstance("" + position, "true");
break;
}
return fragment;
}
#Override
public CharSequence getPageTitle(int position) {
Drawable drawable = getResources().getDrawable(tabIcons[position]);
drawable.setBounds(0, 0, 36, 36);
ImageSpan imageSpan = new ImageSpan(drawable);
SpannableString spannableString = new SpannableString(" ");
spannableString.setSpan(imageSpan, 0, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
return spannableString;
}
#Override
public int getCount() {
return 5;
}
}
}
Tab #1
public class FragmentProfile extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_profile, container,false);
return view;
}
}
Okay after searching for a quite long time, I finally figured out that you were calling setOnPageChangeListener() for ViewPager instead of calling setOnPageChangeListener() for SlidingTabLayout
This question was answered here,
onPageScrolled() not being called
What about havong your main fragment implementing ViewPager.OnPageChangeListener , then you may override onPageSelected

ActionBar is not showing Title in Android

I want to implement Left & Right Side Slider Menu so I have set Right Side Slider in NavigationDrawerSlider which already have Left Side Slider by Default.
I am using ActionBarSherLock for this to support Application from Api 8. Slider is working fine but issue is that ActionBar is not showing Title.
Please help me to solve this issue. One more thing, When I Click on ImageView, It also fires ActionBarDrawerToggle. So, how to prevent this also ?
My Code:
public class MainActivity extends SherlockFragmentActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList_Left;
private ListView mDrawerList_Right;
private ActionBarDrawerToggle mDrawerToggle;
private ActionBar actionBar_Right;
private ArrayList<NavDrawerItem> navDrawerItems_Left;
private ArrayList<NavDrawerItem> navDrawerItems_Right;
private CharSequence mDrawerTitle_Left;
private CharSequence mTitle_Left;
private CharSequence mDrawerTitle_Right;
private CharSequence mTitle_Right;
private String[] mFragmentTitles_Left;
private String[] mFragmentTitles_Right;
private TypedArray navMenuIcons_Left;
private TypedArray navMenuIcons_Right;
private NavDrawerListAdapter adapter_Left;
private NavDrawerListAdapter adapter_Right;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle_Left = mDrawerTitle_Left = getTitle();
mFragmentTitles_Left = getResources().getStringArray(
R.array.nav_drawer_items);
mFragmentTitles_Right = getResources().getStringArray(
R.array.nav_drawer_items_right);
navMenuIcons_Left = getResources().obtainTypedArray(
R.array.nav_drawer_icons);
navMenuIcons_Right = getResources().obtainTypedArray(
R.array.nav_drawer_icons_right);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList_Left = (ListView) findViewById(R.id.list_left_slidermenu);
mDrawerList_Right = (ListView) findViewById(R.id.list_right_slidermenu);
actionBar_Right = getSupportActionBar();
actionBar_Right.setCustomView(R.layout.right_menu);
actionBar_Right.setDisplayShowTitleEnabled(true);
actionBar_Right.setDisplayShowCustomEnabled(true);
navDrawerItems_Left = new ArrayList<NavDrawerItem>();
navDrawerItems_Right = new ArrayList<NavDrawerItem>();
// Left Side Menus...
// Home...
navDrawerItems_Left.add(new NavDrawerItem(mFragmentTitles_Left[0],
navMenuIcons_Left.getResourceId(0, -1)));
navMenuIcons_Left.recycle();
// Right Side Menus...
// Edit Profile...
navDrawerItems_Right.add(new NavDrawerItem(mFragmentTitles_Right[0],
navMenuIcons_Right.getResourceId(0, -1)));
// Change Password...
navDrawerItems_Right.add(new NavDrawerItem(mFragmentTitles_Right[1],
navMenuIcons_Right.getResourceId(1, -1)));
navMenuIcons_Right.recycle();
mDrawerList_Left
.setOnItemClickListener(new DrawerItemClickListener_Left());
mDrawerList_Right
.setOnItemClickListener(new DrawerItemClickListener_Right());
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
adapter_Left = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems_Left);
mDrawerList_Left.setAdapter(adapter_Left);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.app_name, R.string.app_name);
adapter_Right = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems_Right);
mDrawerList_Right.setAdapter(adapter_Right);
ImageView imgRight = (ImageView) findViewById(R.id.imgRightMenu);
imgRight.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (mDrawerLayout.isDrawerOpen(mDrawerList_Right)) {
mDrawerLayout.closeDrawer(mDrawerList_Right);
setTitle(mTitle_Right);
} else {
mDrawerLayout.openDrawer(mDrawerList_Right);
mDrawerLayout.closeDrawer(mDrawerList_Left);
setTitle(mDrawerTitle_Right);
}
}
});
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem_Left(0);
}
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
// getSupportMenuInflater().inflate(R.menu.main, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
if (mDrawerLayout.isDrawerOpen(mDrawerList_Left)) {
mDrawerLayout.closeDrawer(mDrawerList_Left);
setTitle(mTitle_Left);
} else {
mDrawerLayout.openDrawer(mDrawerList_Left);
mDrawerLayout.closeDrawer(mDrawerList_Right);
setTitle(mDrawerTitle_Left);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private class DrawerItemClickListener_Left implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
selectItem_Left(position);
}
}
private void selectItem_Left(int position) {
Fragment newFragment = new Home();
FragmentManager fm = getSupportFragmentManager();
switch (position) {
case 0:
newFragment = new Home();
break;
}
fm.beginTransaction().replace(R.id.frame_container, newFragment)
.commit();
mDrawerList_Left.setItemChecked(position, true);
setTitle(mFragmentTitles_Left[position]);
mDrawerLayout.closeDrawer(mDrawerList_Left);
}
private class DrawerItemClickListener_Right implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
selectItem_Right(position);
}
}
private void selectItem_Right(int position) {
Fragment newFragment = new EditProfile();
FragmentManager fm = getSupportFragmentManager();
switch (position) {
case 0:
newFragment = new EditProfile();
break;
case 1:
newFragment = new ChangePassword();
break;
}
fm.beginTransaction().replace(R.id.frame_container, newFragment)
.commit();
mDrawerList_Right.setItemChecked(position, true);
setTitle(mFragmentTitles_Right[position]);
mDrawerLayout.closeDrawer(mDrawerList_Right);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
I have figured out that It is not showing title because of
actionBar_Right = getSupportActionBar();
actionBar_Right.setCustomView(R.layout.right_menu);
actionBar_Right.setDisplayShowTitleEnabled(true);
actionBar_Right.setDisplayShowCustomEnabled(true);
What to do for this ?
For showing the title in the ActionBar setTitle must be overridden:
#Override
public void setTitle(CharSequence title)
{
this.title = title;
getSupportActionBar().setTitle(title);
}

Can't make NavigationDrawer & FragmentStatePagerAdapter work thogether

I'm trying to use a NavigationDrawer with FragmentStatePagerAdapter for the navigation of my app. The idea is that when clicking on an item of the NavigationDrawer a new fragment opens with two tabs in it.
My problem is that I can't make it work correctly. When clicking on an item of the NavigationDrawer, instead of two tabs I get four, then six, ...
This problem can be solved with actionBar.removeAllTabs(), but my main problem is that when I come back on a previous fragment by re-clicking on the item of the NavigationDrawer (fragment 1 -> fragment 2 -> fragment 1), I got an empty fragment.
I tried to solve this problem by make some changes according to what's stated on other pages, but I didn't succeed in making it work.
Any help would be appreciated, thank you!
Here is the class managing my main fragment:
public class FragmentMultiTab extends SherlockFragment {
private MyVariables mk;
private ActionBar actionBar;
private ViewPager viewPager;
private View rootView;
private int i;
#Override
public View onCreateView(final LayoutInflater inflater,
final ViewGroup container, final Bundle savedInstanceState) {
final int[] fragment = { R.layout.fragment1, R.layout.fragment2,
R.layout.fragment3 };
final int[] pager = { R.id.pager1, R.id.pager2, R.id.pager3 };
this.mk = new MyVariables(this.getArguments());
i = this.mk.getInt("INDEX");
this.rootView = inflater.inflate(fragment[i], container, false);
viewPager = (ViewPager) this.rootView.findViewById(pager[i]);
viewPager.setOnPageChangeListener(onPageChangeListener);
viewPager.setAdapter(new ViewPagerAdapter(getFragmentManager()));
viewPager.getAdapter().notifyDataSetChanged();
addActionBarTabs();
return rootView;
}
private final ViewPager.SimpleOnPageChangeListener onPageChangeListener = new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
super.onPageSelected(position);
actionBar.setSelectedNavigationItem(position);
}
};
private void addActionBarTabs() {
actionBar = getSherlockActivity().getSupportActionBar();
final String[][] tabTitle = {{"Tab 1","Tab 3","Tab 5" },{"Tab 2","Tab 4",
"Tab 6" } };
for (int k = 0; k < 2; k++) {
ActionBar.Tab tab = actionBar.newTab().setText(tabTitle[k][i])
.setTabListener(tabListener);
actionBar.addTab(tab);
}
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
}
private final ActionBar.TabListener tabListener = new ActionBar.TabListener() {
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
};
}
Here is the ViewPager used
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
final int PAGE_COUNT = 2;
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int arg0) {
switch (arg0) {
case 0:
FragmentTab1 fragmenttab1 = new FragmentTab1();
return fragmenttab1;
case 1:
FragmentTab2 fragmenttab2 = new FragmentTab2();
return fragmenttab2;
}
return null;
}
#Override
public int getItemPosition(Object object) {
return PagerAdapter.POSITION_NONE;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return PAGE_COUNT;
}
}
My fragments have the following structure:
<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.support.v4.view.ViewPager
android:id="#+id/pager1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</android.support.v4.view.ViewPager>
</RelativeLayout>
And finally here is my MainActivity:
public class MainActivity extends SherlockFragmentActivity {
DrawerLayout mDrawerLayout;
ListView mDrawerList;
ActionBarDrawerToggle mDrawerToggle;
MenuListAdapter mMenuAdapter;
FragmentMultiTab fragment1 = new FragmentMultiTab();
FragmentMultiTab fragment2 = new FragmentMultiTab();
FragmentMultiTab fragment3 = new FragmentMultiTab();
private final MyVariables mk = new MyVariables();
private int currentPosition;
#Override
public void onConfigurationChanged(final Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
this.mDrawerToggle.onConfigurationChanged(newConfig);
}
// The click listener for ListView in the navigation drawer
private class DrawerItemClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(final AdapterView<?> parent, final View view,
final int position, final long id) {
MainActivity.this.selectItem(position);
}
}
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_main);
currentPosition = -1;
// Locate DrawerLayout in activity_main.xml
this.mDrawerLayout = (DrawerLayout) this
.findViewById(R.id.drawer_layout);
// Locate ListView in activity_main.xml
this.mDrawerList = (ListView) this.findViewById(R.id.listview_drawer);
// Set a custom shadow that overlays the main content when the drawer
// opens
this.mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
// Pass results to MenuListAdapter Class
this.mMenuAdapter = new MenuListAdapter(this);
// Set the MenuListAdapter to the ListView
this.mDrawerList.setAdapter(this.mMenuAdapter);
// Capture button clicks on side menu
this.mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// Enable ActionBar app icon to behave as action to toggle nav drawer
this.getSupportActionBar().setHomeButtonEnabled(true);
this.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
this.mDrawerToggle = new ActionBarDrawerToggle(this,
this.mDrawerLayout, R.drawable.ic_drawer, R.string.drawer_open,R.string.drawer_close) {
#Override
public void onDrawerClosed(final View view) {
// TODO Auto-generated method stub
super.onDrawerClosed(view);
}
#Override
public void onDrawerOpened(final View drawerView) {
// TODO Auto-generated method stub
super.onDrawerOpened(drawerView);
}
};
this.mDrawerLayout.setDrawerListener(this.mDrawerToggle);
if (savedInstanceState == null) {
this.selectItem(0);
}
this.mk.setVariables(this);
}
#Override
public boolean onCreateOptionsMenu(final Menu menu) {
this.getSupportMenuInflater().inflate(R.menu.action_bar_main, menu);
this.getActionBar().setDisplayHomeAsUpEnabled(true);
return true;
}
#Override
public boolean onOptionsItemSelected(final MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
if (this.mDrawerLayout.isDrawerOpen(this.mDrawerList)) {
this.mDrawerLayout.closeDrawer(this.mDrawerList);
} else {
this.mDrawerLayout.openDrawer(this.mDrawerList);
}
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onPostCreate(final Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
this.mDrawerToggle.syncState();
}
private void selectItem(final int position) {
final FragmentTransaction ft = this.getSupportFragmentManager()
.beginTransaction();
if (currentPosition != position)
// Locate Position
switch (position) {
case 0:
this.mk.addInt("INDEX", 0);
this.mk.addBoolean("START", false);
this.fragment1.setArguments(this.mk.getArgs());
ft.replace(R.id.content_frame, this.fragment1);
break;
case 1:
this.mk.addInt("INDEX", 1);
this.fragment2.setArguments(this.mk.getArgs());
ft.replace(R.id.content_frame, this.fragment2);
break;
case 2:
this.mk.addInt("INDEX", 2);
this.fragment3.setArguments(this.mk.getArgs());
ft.replace(R.id.content_frame, this.fragment3);
break;
}
currentPosition = position;
ft.commit();
this.mDrawerList.setItemChecked(position, true);
// Close drawer
this.mDrawerLayout.closeDrawer(this.mDrawerList);
}
}
I'd suggest using the ViewPagerIndicator instead of the standard ActionBar Tabs (they have some issues with regards to being converted into dropdown menus in some cases. The interface is quite simply (you just hook your viewpagerindicator to a viewpager), and you'll probably solve your issue as well.

Categories

Resources