How to Use ViewPager to switch to other layout? - android

public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, i + 1);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0: return getString(R.string.title_section1).toUpperCase();
case 1: return getString(R.string.title_section2).toUpperCase();
case 2: return getString(R.string.title_section3).toUpperCase();
}
return null;
}
}
/**
* A dummy fragment representing a section of the app, but that simply displays dummy text.
*/
public static class DummySectionFragment extends Fragment {
public DummySectionFragment() {
}
public static final String ARG_SECTION_NUMBER = "section_number";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
TextView textView = new TextView(getActivity());
textView.setGravity(Gravity.CENTER);
Bundle args = getArguments();
textView.setText(Integer.toString(args.getInt(ARG_SECTION_NUMBER)));
return inflater.inflate(R.layout.fragment_content1, container, false);
}
}
}
The code above is the template from the SDK for ViewPager, it only put text 1 to 3 when I swipe from one page to one page. The question is how can I replace that text and put my own layout xml when I swipe it, and is it possible to use WebView with this feature. For example: when the activity loads it goes to google.com then when i swipe to other page it change the url of the WebView each time I swipe? Hope someone can help me...

You have to create classes that extend from android.support.v4.app.Fragment just like the class DummySectionFragment. Then, into the method getItem(int i) you should instantiate each class you want for each index and the method getCount() must return the number of Fragments you are instantiating.

viewpager.setCurrentItem(index) where index is the desired fragment index.

Related

Getting blank page on displaying fragment inside a fragment?

This is my fragment which is in navigation menu.
class MirandaFragment extends Fragment {
protected View view;
FragmentPagerAdapter adapterViewPager;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.miranda, container, false);
ViewPager vpPager = (ViewPager) view.findViewById(R.id.vpPager);
adapterViewPager = new MyPageAdapter(getFragmentManager());
vpPager.setAdapter(adapterViewPager);
return view;
}
}
This is the adapter where I has set two fragments EngMiranda and SpaMiranda.
class MyPageAdapter extends FragmentPagerAdapter {
private static int NUM_ITEMS = 2;
public MyPageAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
// Returns total number of pages.
#Override
public int getCount() {
return NUM_ITEMS;
}
// Returns the fragment to display for a particular page.
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return EngMiranda.newInstance("Fragment 1", getCount());
case 1:
return SpaMiranda.newInstance("Fragment 2", getCount());
default:
return null;
}
}
// Returns the page title for the top indicator
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "English";
case 1:
return "Spanish";
default:
return null;
}
}
}
After app gets open for first time then I am able to open the fragment and view the tab fragments in it but when we open that fragment for second time then adapter is not displaying.

SectionsPageAdapter with FragmentPageAdapter

First let me try to reproduce my Problem/Question.
My Activity is a TabbedActivity with 3 Tabs, done with a SectionPageAdapter and a FragmentPageAdapter.
On these 3 Tabs the user is input Data. With just swiping the user can change the tab. After the User has filled in all data, he must click on a FloatingActionButton to save the data.
Now there is my Problem i donĀ“t know if i can access these 3 Fragments with the filled in data ?
Can i load all 3 Fragments with the filled in Data, read the data and save it or must i handle the PageChangeListenEvent and saved the Data before i change the Page?
Code:
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return TravelInfoActivity.PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
return maxTabs;
}
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_FRAGMENT_ID = "fragment_id";
private static int REQUEST_CODE_PLACE = 1;
private View currentRootView;
private View currentClickedView;
#SuppressLint("UseSparseArrays")
private HashMap<Integer, View> hMap = new HashMap<>();
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static TravelInfoActivity.PlaceholderFragment newInstance(int sectionNumber) {
TravelInfoActivity.PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
int fragmentLayout;
switch (sectionNumber) {
case 1:
fragmentLayout = R.layout.fragment_accommodation;
break;
case 2:
fragmentLayout = R.layout.fragment_visited_places;
break;
case 3:
fragmentLayout = R.layout.fragment_additional_info;
break;
default:
fragmentLayout = R.layout.fragment_accommodation;
}
args.putInt(ARG_FRAGMENT_ID, fragmentLayout);
fragment.setArguments(args);
return fragment;
}
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
final View rootView = inflater.inflate(getArguments().getInt(ARG_FRAGMENT_ID), container, false);
currentRootView = rootView;
switch (getArguments().getInt(ARG_FRAGMENT_ID)) {
// switch handling here, not relevant
}
return rootView;
}
Guys i have done it refreshed my brain ;)
Just save the instance from the Fragment to an array and you can use it later.
I made this in the SectionPageAdapter and ovverided the mehtod instantiateItem().
public class SectionsPagerAdapter extends FragmentStatePagerAdapter {
private SparseArray<Fragment> registeredFragments = new SparseArray<>();
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
Integer fragmentId = fragment.getArguments().getInt("fragment_id");
registeredFragments.put(fragmentToPageMap.get(fragmentId), fragment);
return fragment;
}
public Fragment getRegisteredFragment(int position) {
return registeredFragments.get(position);
}
public boolean registeredFragmentExists(int position) {
if(registeredFragments.size() >= position) {
if(registeredFragments.get(position) != null) {
return true;
}
}
return false;
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return TravelInfoActivity.PlaceholderFragment.newInstance(position);
}
#Override
public int getCount() {
return maxTabs;
}
}
Later you can access the fragments rootView with
mSectionsPagerAdapter.getRegisteredFragment(position);
fragment.getActivity().findViewById(id);

How to capture the active section or tab of the swipeable tabs in android?

I'm using swipeable tabs as part of an activity with a total of 3 sections. I'm providing the right and left arrows to navigate to the other sections of the swipe-view.
I want my left arrow to disappear when I'm at the leftmost section and my right-arrow to disappear when I'm at the rightmost section.
Here's what I'm trying rightnow, but not getting the desired result:
public class MainActivity extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
static Button rightButton;
static Button leftButton;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rightButton = (Button)findViewById(R.id.buttonRight);
leftButton = (Button)findViewById(R.id.buttonLeft);
// 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);
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "SECTION 1";
case 1:
return "SECTION 2";
case 2:
return "SECTION 3";
}
return null;
}
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
// Returns a new instance of this fragment for the given section number.
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
int sectionNumber = getArguments().getInt(ARG_SECTION_NUMBER);
String text = instructions(sectionNumber);
textView.setText(text);
return rootView;
}
private String instructions(int sectionNumber) {
if (sectionNumber == 1) {
leftButton.setVisibility(View.INVISIBLE);
rightButton.setVisibility(View.VISIBLE);
Log.i("Welcome"," to section 1");
return "All questions are mandatory. Each question carries 1 mark. There is no negative marking";
}
else if(sectionNumber == 2) {
leftButton.setVisibility(View.VISIBLE);
rightButton.setVisibility(View.VISIBLE);
Log.i("Welcome", " to section 2");
return "Color the bubble besides the option you think is best for the answer.";
}
else {
leftButton.setVisibility(View.VISIBLE);
rightButton.setVisibility(View.INVISIBLE);
Log.i("Welcome", " to section 3");
return "Click on the skip button above to start the test. Timer will start as soon as you'll click that button!";
}
}
}
}
As you can see in the method instructions, I tried using logs to see what's happening only to find that I never get the "Welcome to section 2" part even after swiping through the tabs multiple times. Although, the texts related to a given section are returned correctly. What am I missing here?
The problem is that you returned a new fragment in getItem
Do it like this:
public class SectionsPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragments = new ArrayList<Fragment>();
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
mFragments.add(PlaceholderFragment.newInstance(1));
mFragments.add(PlaceholderFragment.newInstance(2));
mFragments.add(PlaceholderFragment.newInstance(3));
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
}
Also change the Buttons to the fragment_main layout "not" in activity_main and use it like this.
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
private Button rightButton;
private Button leftButton;
// Returns a new instance of this fragment for the given section number.
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
rightButton = (Button)rootView.findViewById(R.id.buttonRight);
leftButton = (Button)rootView.findViewById(R.id.buttonLeft);
int sectionNumber = getArguments().getInt(ARG_SECTION_NUMBER);
String text = instructions(sectionNumber);
textView.setText(text);
return rootView;
}
EDIT if you want to know the cuurent page you have to implement this.
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
Log.i("Welcome", "page "+ position+1);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
Also add the following line so that the system will create your fragment only once:
mViewPager.setOffscreenPageLimit(3);
The issue you had is that you're getting the position that the system created now not the current page.

ARG_SECTION_NUMBER cannot be resolved

I'm currently trying to create 3 different tabs with 3 different fragments for the purpose of having different content for each tab. I'm stuck with some error in my code that says :
ARG_SECTION_NUMBER cannot be resolved
public class SampleFragmentPagerAdapter extends FragmentPagerAdapter {
final int PAGE_COUNT = 3;
private String tabTitles[] = new String[] { "Featured", "Browse", "Following" };
private Context context;
public SampleFragmentPagerAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
#Override
public int getCount() {
return PAGE_COUNT;
}
#Override
public Fragment getItem(int position) {
//(original coding) return PageFragment.newInstance(position + 1);
//getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
switch (position) {
case 0:
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(fragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
case 1:
Fragment fragment2 = new DummySectionFragment2();
Bundle args2 = new Bundle();
//args2.putInt(fragment2.ARG_SECTION_NUMBER, position + 2);
fragment2.setArguments(args2);
return fragment2;
case 2:
Fragment fragment3 = new DummySectionFragment3();
Bundle args3 = new Bundle();
//args3.putInt(fragment3.ARG_SECTION_NUMBER, position + 3);
fragment3.setArguments(args3);
return fragment3;
default:
return null;
}
}
#Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
//(original coding) return tabTitles[position];
Locale l = Locale.getDefault();
switch (position) {
case 0:
return App.getContext().getString(R.string.title_section1).toUpperCase(l);
case 1:
return App.getContext().getString(R.string.title_section2).toUpperCase(l);
case 2:
return App.getContext().getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
Anyone have any idea why ARGS_SECTION_NUMBER cannot be resolved for
fragment.ARG_SECTION_NUMBER
fragment2.ARG_SECTION_NUMBER
fragment3.ARG_SECTION_NUMBER
The DummySectionFragment.java is as follows:
public class DummySectionFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number_1";
public DummySectionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
TextView dummyTextView = (TextView) rootView.findViewById(R.id.section_label);
dummyTextView.setText(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
This is because your fragment variable has type Fragment. But constant is defined in DummySectionFragment. So what you need to do is:
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
Remember that when you use constants defined in some class file, there's no need to access them via instance of the class.

FragmentPagerAdapter class is triggered only when the tab is clicked for the first time

I'm trying to develop a tab based application. Each tab has its fragment. One of them has ViewPager, and ViewPager has its own pages. I move from to another by scrolling in this viewpager.
When I open the application for the first time, there is no problem. However, when I move from this tab, and come to it again, it does not show viewpager content, it does not fire FragmentPagerAdapter class.
Tab A - Tab B - Tab C
Tab C Fragment has ViewPage.
ViewPage has its own pages.
public class FragmentC extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
static ViewPager C_mViewPager;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
C_mViewPager = (ViewPager)inflater.inflate(R.layout.fragmentC, container,false);
C_SectionsPagerAdapter mC_PagerAdapter=new C_SectionsPagerAdapter(MainActivity.fragmentManagerv4);
C_mViewPager.setAdapter(mC_PagerAdapter);
return C_mViewPager;
}
public class C_SectionsPagerAdapter extends FragmentPagerAdapter {
public C_SectionsPagerAdapter (FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
Fragment fragment = null ;
Bundle args;
switch (i) {
case 0:
fragment=new A_SubFragment();
break;
case 1:
fragment = new B_SubFragment();
break;
case 2:
fragment = new C_SubFragment();
break;
case 3:
fragment = new D_SubFragment();
break;
}
return fragment;
}
#Override
public int getCount() {
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0: return getString(R.string.title_section1).toUpperCase();
case 1: return getString(R.string.title_section2).toUpperCase();
case 2: return getString(R.string.title_section3).toUpperCase();
case 3: return getString(R.string.title_section4).toUpperCase();
}
return null;
}
}
public static class A_SubFragment extends Fragment {
public A_SubFragment() {
}
public static final String ARG_SECTION_NUMBER = "section_number";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
RelativeLayout theLayout=(RelativeLayout)inflater.inflate(R.layout.a_sub_fragment, container,false);
//...
return theLayout;}}
}
Fragment C;
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" />
I got the answer, I used FragmentStatePagerAdapter Instead of FragmentPagerAdapter

Categories

Resources