Understanding getItem() in FrameStatePagerAdapter - android

I'm trying to implement sliding tabs in my app following online tutorials. Particularly this one.
What I want to achieve is:
A MainActivity with Sliding Tabs based on a single Fragment. Each tab showing different data. For this I'm trying to get the current position of the tab selected in my fragment but I don't seem to get the correct value. I'm aware of the function that getItem() is called a number of times and sometimes isn't called at all.
So how do I get the current position of the tab selected in fragment? The tutorial I linked passes the position value with the return statement of getItem() but that doesn't seem to be working quite well as I'm getting different value in log and setText.
getItem()
#Override
public Fragment getItem(int position) {
return PageFragment.newInstance(position + 1);
}
PageFragment:
public static PageFragment newInstance(int page) {
Bundle args = new Bundle();
args.putInt(ARG_PAGE, page);
PageFragment fragment = new PageFragment();
fragment.setArguments(args);
return fragment;
}
Position value difference:

I've run into a similar issue and I decided to just completely change the "default" PagerAdapter so that I wouldn't have to mess around with the position myself:
/**
* TabsPagerAdapter.
*
* #author Niels
* #version 1.0
* #since 11-9-2015
*/
public class TabsPagerAdapter extends FragmentPagerAdapter {
/**
* Contains all the fragments.
*/
private List<Fragment> fragments = new ArrayList<>();
/**
* Contains all the tab titles.
*/
private List<String> tabTitles = new ArrayList<>();
/**
* Creates a new PagerAdapter instance.
*
* #param fragmentManager The FragmentManager.
*/
public TabsPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
#Override
public int getCount() {
return fragments.size();
}
#Override
public Fragment getItem(int position) {
return fragments.get(position);
}
#Override
public CharSequence getPageTitle(int position) {
return tabTitles.get(position);
}
/**
* Adds the fragment to the list, also adds the fragment's tab title.
*
* #param fragment New instance of the Fragment to be associated with this tab.
* #param tabTitle A String containing the tab title for this Fragment.
*/
public void addFragment(Fragment fragment, String tabTitle) {
fragments.add(fragment);
tabTitles.add(tabTitle);
}
}
You can use this as such:
#Override
public void onCreate() {
adapter = new TabsPagerAdapter(getSupportFragmentManager()); //TabsPagerAdapter = whatever you named the PagerAdapter
addFragments();
viewpager.setAdapter(adapter); //viewpager = ViewPager view instance
strip.setViewPager(viewpager); //strip = PagerSlidingTabStrip view instance
}
/**
* Adds fragments to the adapter.
*/
private void addFragments() {
adapter.addFragment(new Fragment1(), "Fragment1");
adapter.addFragment(new Fragment2(), "Fragment2");
adapter.addFragment(new Fragment3(), "Fragment3");
adapter.addFragment(new Fragment4(), "Fragment4");
}

Related

Impossible to add or remove pages dinamically from ViewPager Android Activity

I've read all stackOverflow answers regarding this topic, and any of them worked for me, or I couldn't make it myself.
As you can see in the code below, I added the default ViewPager Activity from Android Studio, and now I need to add new pages or remove existing pages from the corresponding buttons.
So, the activity is loading correctly and gets the correct number of pages, and I can also change the information in each of them successfully. As you can see, the app is connected to Firebase and I get from there the total number of pages (dogs) that my activity should have, this is working well.
Now, How can I add a new page, move to that page, and update the adapter and total number of pages?
Same for removing, How can I remove the current page, then move to another one and update the adapter with no problems?
I'm getting totally crazy with this, spent the whole day with diffeent solutions I found in stackoverflow, but could not make it. I'm now confused about when to use the "notifyDataSetChanged()", if it is a good idea override the "getItemPosition" or not, etc.
I would appreciate if someone could finally help me adapting the answer to my project, it's the default ViewPager just modified small parts to try to fix it, but don't know what else I can do.
Thank you in advance and sorry for my english.
Note: Some functions like "updateIntValueFromCurrentUser()" are declared in MainActivity but working, they are related to firebase queries etc so I'm not focusing on this.
public class DummyViewPagerActivity extends MainActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private static ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dummy_view_pager);
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);
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();
}
});
}
//Creating menu bar
#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_dummy_view_pager, menu);
return true;
}
//Creating the two buttons to save and delete the images
#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.
switch (item.getItemId()) {
case R.id.add:
updateIntValueFromCurrentUser("dogs_number", person.getDogs_number()+1);
return true;
case R.id.edit:
return true;
case R.id.delete:
updateIntValueFromCurrentUser("dogs_number", person.getDogs_number()-1);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* 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;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = null;
try {
rootView = inflater.inflate(R.layout.fragment_dummy_view_pager, container, false);
TextView dogName = (TextView) rootView.findViewById(R.id.dog_name);
dogName.setText(allDogs.get((getArguments().getInt(ARG_SECTION_NUMBER)) - 1).getName());
} catch (Exception e) {
Log.e("RaisedException()", e.getMessage());
}
return rootView;
}
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentStatePagerAdapter {
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 getItemPosition(Object object) {
// POSITION_NONE makes it possible to reload the PagerAdapter
return POSITION_NONE;
}
#Override
public int getCount() {
// Show x total pages.
return person.getDogs_number();
}
#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;
}
}
}
Adding/Removing items from FragmentViewPager is a bit tricky thing to do:
Try using this adapter and let me know is it working for you.
public class CodebaseFragmentPagerAdapter extends FragmentStatePagerAdapter {
private List<Fragment> mFragmentList = new ArrayList<Fragment>();
public CodebaseFragmentPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
public void removeItem(int position){
mFragmentList.remove(position == 0 ? 0 : position - 1);
this.notifyDataSetChanged();
}
public void clearAllItems(){
mFragmentList.clear();
this.notifyDataSetChanged();
}
public void updateItem(int position, Fragment fragment){
mFragmentList.set(position, fragment);
notifyDataSetChanged();
}
#Override
public int getItemPosition(Object object) {
if (mFragmentList.contains(object)) return mFragmentList.indexOf(object);
else return POSITION_NONE;
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(Fragment fragment) {
mFragmentList.add(fragment);
notifyDataSetChanged();
}
}

Initialising objects in a fragment of viewpager

I have an application which initiates from a viewPager somewhat like snapchat for reference. Based on the current pattern, which is:
Initialising all the content on fragment is created; the UI thread is being clogged and the application takes a considerable amount of time to initiate.
How do I do it? Since I need to work on these objects on the main thread itself.
In your fragment create a static instance like this
public static FragmentSample newInstance(Datamodel Model) {
FragmentBatch fragment = new FragmentBatch();
Bundle args = new Bundle();
args.putParcelable("extra",Model);
fragment.setArguments(args);
return fragment;
}
and initialize it in the activity's section adapter
public class SampleActivity extends AppCompatActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
Datamodel datamodel;
int batchCount;
List<Datamodel > datamodels;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_weight_record);
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);
datamodels= new ArrayList<>();
datamodels.add(new Datamodel ("Neoperene", "skyperene", "", "22w441",1,"+/-1%",""));
datamodels.add(new Datamodel ("Neoperene", "skyperene", "", "22w442",2,"+/-1%",""));
datamodels.add(new Datamodel ("Neoperene", "skyperene", "", "22w443",3,"+/-1%",""));
}
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).
switch(position){
case 0:
return FragmentSample.newInstance(Datamodel.get(0));
case 1:
return FragmentBatch.newInstance(Datamodel.get(1));
default:
return FragmentBatch.newInstance(Datamodel.get(0));
}
#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;
}
}
}

How to create android navbar?

I've tried following guides with ViewPager and slidingtablayout but they don't seem to work or are deprecated. Now what is the actual best way to create tabs on an android template?
Or can someone point me to a guide/tutorial with a simple clear explanation?
Creating tabs can be done very easily with a library that was made for just that:
astuetz' PagerSlidingTabStrip
Add the dependancy to your app's (NOT project's) build.gradle:
dependencies {
compile 'com.astuetz:pagerslidingtabstrip:1.0.1'
}
Include a PagerSlidingTabStrip widget to your layout (XML), this is typically placed above the ViewPager it represents:
<com.astuetz.PagerSlidingTabStrip
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="48dip" />
Create a ViewPager adapter:
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import java.util.ArrayList;
import java.util.List;
/**
* TabsPagerAdapter.
*
* #author Niels
* #version 1.0
* #since 11-9-2015
*/
public class TabsPagerAdapter extends FragmentPagerAdapter {
/**
* Contains all the fragments.
*/
private List<Fragment> fragments = new ArrayList<>();
/**
* Contains all the tab titles.
*/
private List<String> tabTitles = new ArrayList<>();
/**
* Creates a new PagerAdapter instance.
*
* #param fragmentManager The FragmentManager.
*/
public TabsPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
#Override
public int getCount() {
return fragments.size();
}
#Override
public Fragment getItem(int position) {
return fragments.get(position);
}
#Override
public CharSequence getPageTitle(int position) {
return tabTitles.get(position);
}
/**
* Adds the fragment to the list, also adds the fragment's tab title.
*
* #param fragment New instance of the Fragment to be associated with this tab.
* #param tabTitle A String containing the tab title for this Fragment.
*/
public void addFragment(Fragment fragment, String tabTitle) {
fragments.add(fragment);
tabTitles.add(tabTitle);
}
}
And finally, in your activity's onCreate:
//adapter = view.findViewById(...)
//viewpager = view.findViewById(...)
adapter = new TabsPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new FragmentTab1() "Tab 1");
adapter.addFragment(new FragmentTab2(), "Tab 2");
adapter.addFragment(new FragmentTab3(), "Tab 3");
adapter.addFragment(new FragmentTab4(), "Tab 4");
viewpager.setAdapter(adapter);
strip.setViewPager(viewpager);

Using Tabs and Fragments to display my Layouts

i have an existing App and i want to add tabs to navigate between layouts
i did found several tutorials and topic on the same subject but am beginner on Android and i found some dificults to do this so i hape if someone can help me do it
btw i did use the TabbedActivity in Android studio it did add tabs but i don't know how to implements layouts to those tabs and still have the Tab bar cause i did this
if(tab.getPosition()==0){
Intent intent = new Intent("com.blooddonor.blooddonor.profil");
startActivity(intent);
}
and i don't won't things to be liek those it opens another tabs not displayed on the principale layout that have the tabs
You want to use fragments and not activities to use tab navigation. What you are doing is launching a new activity which will not have the tab navigation enabled. I'd suggest creating a tabbed activity and looking at how it's constructed. Here's a very basic tabbed navigation from the stock sample.
public class TabbedActivity extends Activity implements ActionBar.TabListener {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v13.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabbed);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// set up your tabs here instead using this for loop
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(
actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Here is where you would implement which fragment to set
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
default:
return null;
}
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_placeholder, container, false);
return rootView;
}
}
}

How do I implement this swipe navigation bar?

I wanted to add the swipe nav bar which is as shown in the GIF, to my app.
EDIT:
public class MainActivity extends FragmentActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link android.support.v4.app.FragmentPagerAdapter} derivative, which
* will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
/**
* 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 DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public static class DummySectionFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public DummySectionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_dummy, container, false);
TextView dummyTextView = (TextView) rootView.findViewById(R.id.section_label);
dummyTextView.setText(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
}
I tried the following code to implement this nav bar, basically it has a title strip and navigation bar, But now.. How do I use different layouts for different navigation swipes?
Thanks for any help!
Look into ViewPager and FragmentPagerAdapter from the support libraries.
http://developer.android.com/reference/android/support/v4/view/ViewPager.html
http://developer.android.com/reference/android/support/v4/app/FragmentPagerAdapter.html
You need a ViewPager, Fragments and PagerTitleStrip
You can read about that here:
http://developer.android.com/training/implementing-navigation/lateral.html#PagerTitleStrip
I strongly recommend for you to learn how to use and deal with Fragments in an App, if you aren't using them already. It's needed in a ViewPager.

Categories

Resources