Issue while changing fragment in ViewPager - android

I am trying to change/slide fragment on click of a button in ViewPager. My code works in one project but, not in current.
xml of activity to load fragment:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/content_swipe"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="firebasetest.imranrana.android.firebasetest.SwipeActivity"
tools:showIn="#layout/activity_swipe"
android:orientation="vertical"
>
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/viewPagerId"
>
</android.support.v4.view.ViewPager>
</LinearLayout>
activity:
public class SwipeActivity extends AppCompatActivity{
ViewPager viewPager;
Toolbar toolbar;
TabLayout tabLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_swipe);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().hide();
viewPager=(ViewPager)findViewById(R.id.viewPagerId);
setupViewPager(viewPager);
// tabLayout=(TabLayout)findViewById(R.id.tabLayoutId);
// tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new WebViewFragment()/*, "Main"*/);
adapter.addFragment(new MenuFragment()/*, "TWO"*/);
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentStatePagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
// private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment/*, String title*/) {
mFragmentList.add(fragment);
// mFragmentTitleList.add(title);
}
/*#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}*/
}
}
fragment of viewpager contains changing button:
public class MenuFragment extends Fragment {
Button funPageButton;
Button profilePageButton;
Fragment fragment;
FragmentTransaction fragmentTransaction;
public MenuFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view=inflater.inflate(R.layout.fragment_menu, container, false);
funPageButton=(Button)view.findViewById(R.id.funPageButtonId);
profilePageButton=(Button)view.findViewById(R.id.profileButtonId);
funPageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(),"test",Toast.LENGTH_LONG).show();
fragment=new TestFragment();
fragmentTransaction=getActivity().getSupportFragmentManager().beginTransaction(); ;
fragmentTransaction.replace(R.id.content_swipe,fragment).commit();
}
});
profilePageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(),"test 1",Toast.LENGTH_LONG).show();
fragment=new TestFragment1();
fragmentTransaction=getFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.content_swipe,fragment).commit();
}
});
return view;
}
}
What am i doing wrong?

Related

cannot find fragment from viewpager

there is a fragment in my activity in which there is a viewpager which has 5 fragments in it and inside the main activity i need to get one of the fragment from viewpager
Activity
public class MainActivity extends AppCompatActivity {
public void setFragment(){
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
mainFragment= new MainFragment();
FragmentTransaction fragmentTransaction =getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.container, mainFragment,"mainFragment");
fragmentTransaction.commitAllowingStateLoss();
}
}, 250);
}
public void findFragment() {
mainFragment= (MainFragment) getSupportFragmentManager().findFragmentByTag("mainFragment");
viewPager = mainFragment.viewPager;
FragmentOne fragment = (FragmentOne) getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.viewPager + ":" + viewPager.getCurrentItem());
}
}
MainFragment
public class MainFragment extends Fragment{
private void initViewPagerAndTabs() {
viewPager = view.findViewById(R.id.viewPager);
pagerAdapter = new PagerAdapter(getChildFragmentManager());
pagerAdapter.addFragment(FragmentOne.newInstance(), "one");
pagerAdapter.addFragment(FragmentTwo.newInstance(), "two");
pagerAdapter.addFragment(FragmentThree.newInstance(), "three");
pagerAdapter.addFragment(FragmentFour.newInstance(), "four");
pagerAdapter.addFragment(FragmentFive.newInstance(), "five");
viewPager.setAdapter(pagerAdapter);
TabLayout tabLayout = view.findViewById(R.id.tabLayout);
tabLayout.setupWithViewPager(viewPager);
viewPager.setCurrentItem(1);
viewPager.setOffscreenPageLimit(3);
}
private static class PagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> fragmentList = new ArrayList<>();
private final List<String> fragmentTitleList = new ArrayList<>();
private PagerAdapter(FragmentManager fm) {
super(fm);
}
public void addFragment(Fragment fragment, String title) {
fragmentList.add(fragment);
fragmentTitleList.add(title);
}
#Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
#Override
public int getCount() {
return fragmentList.size();
}
#Override
public CharSequence getPageTitle(int position) {
return fragmentTitleList.get(position);
}
}
}
if i use "getFragmentManager()" instead of "getChildFragmentManager()" then it returns the fragment but when i use "getChildFragmentManager()" in viewPager it returns null in activity
Try this Running Code for 1 fragment, may it helps you in your code :
Main Activity
public class OpenQuran extends AppCompatActivity implements TabLayout.OnTabSelectedListener {
TabLayout tabLayoutqaue;
Pager mAdapter;
MediaPlayer mp;
//This is our viewPagerss
ViewPager viewPager;
View mWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_open_quran);
Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle("Read Quran");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//Initializing the tablayout
tabLayoutqaue = (TabLayout) findViewById(R.id.tabLayoutqaue);
//Initializing viewPager
viewPager = (ViewPager) findViewById(R.id.pager);
//Creating our pager adapter
mAdapter = new Pager(getSupportFragmentManager());
// 1 Fragment
mAdapter .addFrag(new Quran(), "Quran");
viewPager.setAdapter(mAdapter);
tabLayoutqaue.setupWithViewPager(viewPager);
tabLayoutqaue.setOnTabSelectedListener(this);
}
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
Fargment Class :
public class parahlist extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//Returning the layout file after inflating
//Change R.layout.tab1 in you classes
return inflater.inflate(R.layout.activity_parahlist, container, false);}
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
}
View Pager Class:
public class Pager extends FragmentPagerAdapter {
//integer to count number of tabs
int tabCount;
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
//Constructor to the class
public Pager(FragmentManager fm) {
super(fm);
//Initializing tab count
this.tabCount= tabCount;
}
//Overriding method getItem
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(Fragment Fragment, String title) {
mFragmentList.add(Fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
Now This the code Of MainActivity, 2nd Fragment and 3rd one is View Pager class. You dont need to change or edit your View Pager Class. Just Create Java Class and Paste that code as it is.
In Main Activity the Line : mAdapter .addFrag(new Quran(), "Quran"); adding description and Fragment. You can add your own fragment after "new".
After that you have to put Tablayout widget in you Xml as Follows:
<android.support.design.widget.TabLayout
android:id="#+id/tabLayoutqaue"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorgreen"
android:minHeight="?attr/actionBarSize"
app:tabIndicatorColor="#color/colorback"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
And View Pager like:
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:adjustViewBounds="true"
/>
You may face some issue regarding tablayout :
Just put this line in your gradle build under dependecies:
compile 'com.android.support:design:25.3.1'
According to your version. for example you have 25.0.1
then line will be :
compile 'com.android.support:design:25.0.1
Still i m here to tell you more. if you got problem!

Hide AppBarLayout using toolbar in fragment in Android

This is my manifest
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
This is my some part of MainActivity.java
public class MainActivity extends AppCompatActivity {
FragmentManager fragmentManager;
FragmentTransaction fragmentTransaction;
Fragment fragment,recepie_fragment,products_fragment,swadeshi_fragment,previous;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_yash);
//setSupportActionBar(toolbar);
//setSupportActionBar(null);
// final View ab=(View)findViewById(R.id.appbarmain);
fragmentManager = getSupportFragmentManager();
fragmentTransaction=fragmentManager.beginTransaction();
recepie_fragment=new Recepie_Fragment();
products_fragment=new Products_Fragment();
swadeshi_fragment=new Swadeshi_Fragment();
fragment=recepie_fragment;//new Fragment();
fragmentTransaction.replace(R.id.bglayout,fragment);
fragmentTransaction.commit();
previous=fragment;
BottomBar bb=BottomBar.attach(this,savedInstanceState);
bb.setActiveTabColor("RED");
bb.setItemsFromMenu(R.menu.bottom_buttons, new OnMenuTabSelectedListener() {
#Override
public void onMenuItemSelected(int menuItemId) {
fragmentTransaction=fragmentManager.beginTransaction();
switch(menuItemId)
{
case R.id.button1:
previous=fragment;
// ab.setAlpha(0);
fragment=recepie_fragment;//new Recepie_Fragment();
// fragment.setRetainInstance(true);
break;
case R.id.button2:
//getSupportActionBar().show();
previous=fragment;
fragment=products_fragment;//new Products_Fragment();
//fragment.setRetainInstance(true);
break;
case R.id.button3:
previous=fragment;
//getSupportActionBar().show();
fragment=swadeshi_fragment;//new Swadeshi_Fragment();
//fragment.setRetainInstance(true);
break;
}
fragmentTransaction.replace(R.id.bglayout,fragment);
fragmentTransaction.commit();
}
});
}
Here is my RecepieFragment.java
public class Recepie_Fragment extends Fragment {
View rootView;
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
int logo_ids[]={R.drawable.main_course,R.drawable.cakes,R.drawable.specials};
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
void setupTabIcons()
{
tabLayout.getTabAt(0).setIcon(logo_ids[0]);
tabLayout.getTabAt(1).setIcon(logo_ids[1]);
tabLayout.getTabAt(2).setIcon(R.drawable.extra);
// tabLayout.getTabAt(1).setCustomView();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//getActivity().getApplication().setTheme(R.style.AppTheme_NoActionBar);
rootView=inflater.inflate(R.layout.recepie_viewpager, container, false);
//getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
toolbar=(Toolbar)rootView.findViewById(R.id.toolbar_yash);
// ((AppCompatActivity) getActivity()).findViewById(R.id.toolbar_yash).animate().translationY(-(R.id.toolbar_yash).getBottom()).setInterpolator(new AccelerateInterpolator()).start();
viewPager = (ViewPager)rootView.findViewById(R.id.viewpager);
setupViewPager(viewPager);
setRetainInstance(true);
viewPager.setOffscreenPageLimit(3);
tabLayout = (TabLayout)rootView. findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
setupTabIcons();
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
//actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
private int previousState, currentState;
#Override
public void onPageScrollStateChanged(int state) {
int currentPage = viewPager.getCurrentItem(); //ViewPager Type
if (currentPage == 2 || currentPage == 0) {
previousState = currentState;
currentState = state;
if (previousState == 1 && currentState == 0) {
viewPager.setCurrentItem(currentPage == 0 ? 2 : 0);
}
}
}
});
return rootView;
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getChildFragmentManager());//(getActivity().getSupportFragmentManager());
adapter.addFrag(new Main_Course(), "");
adapter.addFrag(new Cakes(), "");
adapter.addFrag(new Specials(), "");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
And this the xml file i am using :
tools:context=".activity.activity.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/appbarmain"
android:theme="#style/AppTheme.NoActionBar">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar_yash"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.NoActionBar" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_main" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
Below type of visualisation is created when I'm trying to hide the toolbar/actionbar in recepies fragment. What I want is whenever I move into products or swadeshi fragment I get this action bar but when in recepie fragment my actionbar hides and screen consists of my viewpager of 3 elements as shown of cake but instead a blank is created.

Tabs with in the Tabs in android studio

I just want to implements Tabs with in the Tabs. If it is possible than please share the code
See image below for reference
This is the answer of my question. I set the tabs with in the Tabs. Basically set the tab in fragment:
My java code:
public class SD extends Fragment {
View view;
PagerAdapter adapter;
public SD() {
// Required empty public constructor
}
private void setupViewPager(ViewPager viewPager) {
///Here we have to pass ChildFragmentManager instead of FragmentManager.
adapter = new PagerAdapter(getChildFragmentManager());
adapter.addFragment(new Sim1Detail(), "Sim 1");
adapter.addFragment(new Sim2Detail(), "Sim 2");
viewPager.setAdapter(adapter);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.sd, container, false);
super.onCreate(savedInstanceState);
// ButterKnife.bind(getActivity(), view);
final ViewPager viewPager = ButterKnife.findById(view, R.id.viewpager);
setupViewPager(viewPager);
TabLayout tabLayout = ButterKnife.findById(view, R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
return view;
}
#Override
public void onDestroyView() {
super.onDestroyView();
// ButterKnife.unbind(getActivity);
}
static class PagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragments = new ArrayList<>();
private final List<String> mFragmentTitles = new ArrayList<>();
public PagerAdapter(FragmentManager fm) {
super(fm);
}
public void addFragment(Fragment fragment, String title) {
mFragments.add(fragment);
mFragmentTitles.add(title);
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return mFragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitles.get(position);
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabGravity="fill"
app:tabMode="fixed" />
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
here it is ..

PagerSlidingTabStrip shows wrong ViewPager

I have used fragments for drawer item, each fragments consists of non-fixed tabs.I'm using PagerSlidingTabStrip library for showing tabs.When fragment is initialized it shows 1st ViewPager, which is correct but when I click on 2nd tab it shows up 3rd ViewPager.Likewise the last ViewPager is never shown.
Tab xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.astuetz.PagerSlidingTabStrip
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="48dp"
android:textColor="#000000"
android:textSize="#dimen/sp_fifteen"
app:pstsDividerColor="#color/red"
app:pstsIndicatorColor="#color/black"
app:pstsTextAllCaps="true"
app:pstsUnderlineColor="#color/gray" />
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
Adapter class:
private PagerSlidingTabStrip tabStrip;
private Adapter adapter;
public static TowerOneTabs newInstance() {
TowerOneTabs fragment = new TowerOneTabs();
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View mView = getActivity().getLayoutInflater().inflate(R.layout.tower_tabs_layout, null);
super.onCreate(savedInstanceState);
ViewPager viewPager = (ViewPager) mView.findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabStrip = (PagerSlidingTabStrip) mView.findViewById(R.id.tabs);
tabStrip.setViewPager(viewPager);
tabStrip.setOnPageChangeListener(this);
return mView;
}
#Override
public void onResume() {
super.onResume();
tabStrip.setOnPageChangeListener(this);
}
#Override
public void onDestroyView() {
super.onDestroyView();
}
private void setupViewPager(ViewPager viewPager) {
//Here we have to pass ChildFragmentManager instead of FragmentManager.
adapter = new Adapter(getChildFragmentManager());
adapter.addFragment(TowerOne.newInstance(), getResources().getString(R.string.tower1));
adapter.addFragment(T11.newInstance(), Constants.KEY_T1_1);
adapter.addFragment(T12.newInstance(), Constants.KEY_T1_2);
adapter.addFragment(T13.newInstance(), Constants.KEY_T1_3);
adapter.addFragment(T14.newInstance(), Constants.KEY_T1_4);
adapter.addFragment(T15.newInstance(), Constants.KEY_T1_5);
viewPager.setAdapter(adapter);
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
switch (position) {
case 0:
// BaseActivity.getTitleView().setText(Constants.KEY_TOWER_ONE);
break;
case 1:
mCallback.showDialog();
break;
case 2:
mCallback.showDialog();
break;
case 3:
mCallback.showDialog();
break;
case 4:
mCallback.showDialog();
break;
case 5:
mCallback.showDialog();
break;
default:
break;
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
static class Adapter extends FragmentPagerAdapter {
private final List<Fragment> mFragments = new ArrayList<>();
private final List<String> mFragmentTitles = new ArrayList<>();
public Adapter(android.support.v4.app.FragmentManager fm) {
super(fm);
}
public void addFragment(Fragment fragment, String title) {
mFragments.add(fragment);
mFragmentTitles.add(title);
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return mFragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitles.get(position);
}
}
I checked this code and its working. If you want to add extra parameter (like Constant), you can edit the SampleFragmentPagerAdapter's addFragment method.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
//viewPager.setAdapter(new SampleFragmentPagerAdapter(getSupportFragmentManager()));
setupViewPager(viewPager);
// Give the PagerSlidingTabStrip the ViewPager
PagerSlidingTabStrip tabsStrip = (PagerSlidingTabStrip) findViewById(R.id.tabs);
// Attach the view pager to the tab strip
tabsStrip.setViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
SampleFragmentPagerAdapter adapter = new SampleFragmentPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new OneFragment(), "ONE");
adapter.addFragment(new TwoFragment(), "TWO");
viewPager.setAdapter(adapter);
}
public class SampleFragmentPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public SampleFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return mFragmentList.size();
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}

How to load the fragments when the tab is selected or page is swiped

when I am swiping tabs are changing but fragment that I attached is not loading.
I have created 4 fragments and their layouts
I have included pagerAdapter in the mainActivity class
output(showing blank page when tab is selected)
Here is my MainActivity.java
public class MainActivity extends AppCompatActivity {
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
tabLayout = (TabLayout) findViewById(R.id.tab_layout);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout.setupWithViewPager(viewPager);
tabLayout.setOnTabSelectedListener(onTabSelectedListener(viewPager));
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new FragmentOne(), "Home");
adapter.addFragment(new FragmentTwo(), "e-Profile");
adapter.addFragment(new FragmentThree(), "Results");
adapter.addFragment(new FragmentFour(), "Outpass");
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
onTabSelectedListener(viewPager);
}
private TabLayout.OnTabSelectedListener onTabSelectedListener(final ViewPager pager) {
return new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
pager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
};
}
}
this is my viewpagerAdapter.
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
MyFragment
public class FragmentOne extends Fragment{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_one, container, false);
}
}
Please follow the following code it will work.Compare ur code with this.It will perfectly work for me.
My Activity:
public class MainActivity extends AppCompatActivity {
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
tabLayout.setOnTabSelectedListener(onTabSelectedListener(viewPager));
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();
}
});
}
private TabLayout.OnTabSelectedListener onTabSelectedListener(final ViewPager viewPager) {
return new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
};
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new OneFragment(), "ONE");
adapter.addFragment(new TwoFragment(), "TWO");
adapter.addFragment(new ThreeFragment(), "THREE");
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
onTabSelectedListener(viewPager);
}
#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;
}
return super.onOptionsItemSelected(item);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:fitsSystemWindows="true"
tools:context=".MainActivity">
<android.support.design.widget.AppBarLayout android:layout_height="wrap_content"
android:layout_width="match_parent" android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar android:id="#+id/toolbar"
android:layout_width="match_parent" android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary" app:popupTheme="#style/AppTheme.PopupOverlay" />
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="fixed"
app:tabGravity="fill"/>
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_main" />
<android.support.design.widget.FloatingActionButton android:id="#+id/fab"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_gravity="bottom|end" android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
content_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:showIn="#layout/activity_main" tools:context=".MainActivity">
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</RelativeLayout>
OneFragment.java
public class OneFragment extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// View view = inflater.inflate(R.layout.frag_one,container,false);
return inflater.inflate(R.layout.frag_one,container,false);
}
}
frag_one.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:text="First Fragment"/>
</LinearLayout>
Same like on your code ontabselected you set current item of viewpager here also in on pageselected you have to replace your fragment
eventPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int arg0) {
if (arg0 == 0) {
// replace fragmen1
}
if (arg0 == 1) {
// replace fragment 2
}
if (arg0 == 2) {
// replace fragment 3
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
});
Remove these line of codes and it should work.
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
onTabSelectedListener(viewPager);
Return the view properly in fragment:) Woolla it should work:)
public class ThreeFragment extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.frag_three,container,false);
return view;
}
}

Categories

Resources