I have this problem as you can see in the pictures below:
1) http://imageshack.us/photo/my-images/19/schermata20120512a09444.png/
2) http://imageshack.us/photo/my-images/651/schermata20120512a09444.png/
I have done one viewpager with three fragment , but when scroll, I see one of them, i would see two fragments.
my cose is:
public class FragmentProjetSwipePageActivity extends FragmentActivity {
// derived from http://thepseudocoder.wordpress.com/2011/10/05/android-page-swiping-using-viewpager/
// list contains fragments to instantiate in the viewpager
List<Fragment> fragmentsV1 = new Vector<Fragment>();
// page adapter between fragment list and view pager
private PagerAdapter mPagerAdapter;
// view pager
private ViewPager mPager;
// activity data
public String p2text,p3text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// creating fragments and adding to list
fragmentsV1.add(Fragment.instantiate(this,Page1Fragment.class.getName()));
fragmentsV1.add(Fragment.instantiate(this,Page2Fragment.class.getName()));
fragmentsV1.add(Fragment.instantiate(this,Page3Fragment.class.getName()));
// creating adapter and linking to view pager
mPager = (ViewPager) super.findViewById(R.id.pager1);
this.mPagerAdapter = new PagerAdapter(super.getSupportFragmentManager(),fragmentsV1,this );
mPager.setAdapter(this.mPagerAdapter);
//Set a listener that will be invoked whenever the page changes or is incrementally scrolled.
}
}
PagerAdapter.java
public class PagerAdapter extends FragmentPagerAdapter {
// fragments to instantiate in the viewpager
private List<Fragment> fragments;
FragmentManager fm;
private static int NUM_PAGER_VIEWS = 2;
Context contex;
// constructor
public PagerAdapter(FragmentManager _fm,List<Fragment> fragments) {
super(_fm);
this.fragments = fragments;
fm=_fm;
}
// return access to fragment from position, required override
#Override
public Fragment getItem(int position) {
return this.fragments.get(position);
}
// number of fragments in list, required override
#Override
public int getCount() {
return NUM_PAGER_VIEWS;
//return this.fragments.size();
}
}
thanks
Related
I set up a tab slider in my activity calling 3 separate fragments depending on the fragment selected. The problem is that when the first tab is selected, "Science" is shown - which was set on the onCreateView() method of the first fragment. However, WITHOUT clicking on the other tabs, "Technology" and "Sports" are then shown.
To my knowledge, the way I implemented it the last two should only show once the corresponding tab is selected.
This is my Page adapter class
public class PagerAdapter extends FragmentPagerAdapter {
final int PAGE_COUNT = 3; //Represents the number of tabs
private String tabTitles[] = new String[]{"Technology", "Science", "Sports"}; //Tab values defined in an array
private Context context;
public PagerAdapter(FragmentManager fm, Context context)
{
super(fm);
this.context = context;
}
#Override
public int getCount()
{
return PAGE_COUNT;
}
//determines the fragment depending on the selected tab
#Override
public Fragment getItem(int position)
{
if(position==0)
return TechnologyFragment.newInstance(position+1);
else if(position==1)
return ScienceFragment.newInstance(position+1);
else if(position==2)
return SportsFragment.newInstance(position+1);
else
return null;
}
//displays the title for each tab
#Override
public CharSequence getPageTitle(int position)
{
// Generate title based on item position
return tabTitles[position];
}
}
This is the news class - where the view pager and tab layout are set up
public class News extends AppCompatActivity {
//Here the viewPager is connected to the PagerAdapter class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news);
//This component will be used to page between the various fragments created.
final ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setAdapter(new PagerAdapter(getSupportFragmentManager(), News.this));
//the tabLayout is given the viewPager to connect to the pager with the tabs
TabLayout tabLayout = (TabLayout) findViewById(R.id.sliding_tabs);
tabLayout.setupWithViewPager(viewPager);
//the following was used so the tabs fill up the width of the screen being responsive for all devices and orientations
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
tabLayout.setTabMode(TabLayout.MODE_FIXED);
}
}
And these are the fragment classes - (the other two are identical but have a different message represented using the Toast)
public class ScienceFragment extends Fragment {
//other methods
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_science_fragment, container, false);
toShow=getAll();
GridView gridView = (GridView)view.findViewById(R.id.gridview);
gridView.setAdapter(new ImageAdapter(getContext(),toShow));
Toast.makeText(getContext(), "Science", Toast.LENGTH_SHORT).show();
return view;
}
}
Any help is appreciated
I have a viewpager app that I am working on with 3 fragments.
I am adding the fragments dynamically via the FragmentStatePagerAdapter like that:
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
CharSequence Titles[]; // This will Store the Titles of the Tabs which are Going to be passed when ViewPagerAdapter is created
int NumbOfTabs; // Store the number of tabs, this will also be passed when the ViewPagerAdapter is created
// Build a Constructor and assign the passed Values to appropriate values in the class
public ViewPagerAdapter(FragmentManager fm,CharSequence mTitles[], int mNumbOfTabsumb) {
super(fm);
this.Titles = mTitles;
this.NumbOfTabs = mNumbOfTabsumb;
}
//This method return the fragment for the every position in the View Pager
#Override
public Fragment getItem(int position) {
if(position == 0) // if the position is 0 we are returning the First tab
{
Current_forecast_fragment current_forecast_fragment = new Current_forecast_fragment();
return current_forecast_fragment;
}
else if (position == 1) // As we are having 2 tabs if the position is now 0 it must be 1 so we are returning second tab
{
return new Hourly_forecast_fragment();
}else {
return new Daily_forecast_fragment();
}
}
// This method return the titles for the Tabs in the Tab Strip
#Override
public CharSequence getPageTitle(int position) {
return Titles[position];
}
// This method return the Number of tabs for the tabs Strip
#Override
public int getCount() {
return NumbOfTabs;
}
}
How do I reference a fragment, lets say the current forecast one from my main activity? I tried something like that but I need the fragment id to reference it. Any suggestions?:
public class MainActivity extends AppCompatActivity {
ViewPager pager;
ViewPagerAdapter adapter;
SlidingTabLayout tabs;
CharSequence Titles[]={"Current","Hourly","Daily"};
int Numboftabs =3;
Current_forecast_fragment mCurrent_forecast_fragment;
public static final String TAG = MainActivity.class.getSimpleName();
public static final String LOCATION_KEY = "location_key";
public Forecast mForecast;
public static final String DAILY_FORECAST = "DAILY_FORECAST";
public static final String HOURLY_FORECAST = "HOURLY_FORECAST";
//default coordinates - Gotse Delchev, UK Lati:57.156866 ; Long:
private double latitude = 41.5667;
private double longitude = 23.7333;
private LocationManager locationManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//-----------MY CODE STARTS HERE-----------------
mCurrent_forecast_fragment = (Current_forecast_fragment) getSupportFragmentManager().findFragmentById(R.id.??????);
//Log.d("MainActivity",mCurrent_forecast_fragment.getTag() + "Georgi");
getLocation();
// Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
adapter = new ViewPagerAdapter(getSupportFragmentManager(),Titles,Numboftabs);
// Assigning ViewPager View and setting the adapter
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(adapter);
// Assiging the Sliding Tab Layout View
tabs = (SlidingTabLayout) findViewById(R.id.tabs);
tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width
// Setting Custom Color for the Scroll bar indicator of the Tab View
tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.tabsScrollColor);
}
});
// Setting the ViewPager For the SlidingTabsLayout
tabs.setViewPager(pager);
}
}
After a lot of experimentation I came with a simple solution to my problem. Since I am adding the fragments dynamically (in the viewPagerAdapter) and not in XML I couldn't reference them weither by id or tag. My solution is to modify slightly the adapter so that it stores a reference of the fragment passed as a parameter. Then all of the methods of the fragment are accessible (if declired public) in the mainActivity:
MainActivity:
public class MainActivity extends AppCompatActivity {
ViewPager pager;
ViewPagerAdapter adapter;
SlidingTabLayout tabs;
CharSequence Titles[]={"Current","Hourly","Daily"};
int Numboftabs =3;
Current_forecast_fragment mCurrent_forecast_fragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//-----------MY CODE STARTS HERE-----------------
this.mCurrent_forecast_fragment = new Current_forecast_fragment();
// Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
adapter = new ViewPagerAdapter(getSupportFragmentManager(),Titles,Numboftabs,mCurrent_forecast_fragment);
// Assigning ViewPager View and setting the adapter
pager = (ViewPager) findViewById(R.id.pager);
pager.setOffscreenPageLimit(3);
pager.setAdapter(adapter);
// Assiging the Sliding Tab Layout View
tabs = (SlidingTabLayout) findViewById(R.id.tabs);
tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width
// Setting Custom Color for the Scroll bar indicator of the Tab View
tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.tabsScrollColor);
}
});
// Setting the ViewPager For the SlidingTabsLayout
tabs.setViewPager(pager);
}
My Code in ViewPagerAdapter:
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private Current_forecast_fragment mCurrent_forecast_fragment;
CharSequence Titles[]; // This will Store the Titles of the Tabs which are Going to be passed when ViewPagerAdapter is created
int NumbOfTabs; // Store the number of tabs, this will also be passed when the ViewPagerAdapter is created
// Build a Constructor and assign the passed Values to appropriate values in the class
public ViewPagerAdapter(FragmentManager fm,CharSequence mTitles[], int mNumbOfTabsumb,Current_forecast_fragment current_fragment) {
super(fm);
this.mCurrent_forecast_fragment = current_fragment;
this.Titles = mTitles;
this.NumbOfTabs = mNumbOfTabsumb;
}
//This method return the fragment for the every position in the View Pager
#Override
public Fragment getItem(int position) {
if(position == 0) // if the position is 0 we are returning the First tab
{
return this.mCurrent_forecast_fragment;
}
else if (position == 1) // As we are having 2 tabs if the position is now 0 it must be 1 so we are returning second tab
{
return new Hourly_forecast_fragment();
}else {
return new Daily_forecast_fragment();
}
}
}
i working viewpager.i have 4 fragments and add there fragments in viepager.but i want to add fragments dinamically
Here is my adapter
public class MyPagerAdapter extends FragmentPagerAdapter {
private List<Fragment> fragments;
public MyPagerAdapter(FragmentManager fm) {
super(fm);
this.fragments = new ArrayList<Fragment>();
for (int i = 0; i < 10; i++) {
fragments.add(new FragmentBlue());
}
}
#Override
public Fragment getItem(int position) {
return fragments.get(position);
}
#Override
public int getCount() {
return fragments.size();
}
}
And here is the activity
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyPagerAdapter pageAdapter = new MyPagerAdapter(getSupportFragmentManager());
ViewPager pager = (ViewPager)findViewById(R.id.myViewPager);
pager.setAdapter(pageAdapter);
}
}
how i can add fragments dynamically instead of static GetCountSize(). for more information, i want to add 10 fragments in viewpager and each fragments background wast be different.
Consider using ViewPager2. By design it allows to modify fragments collection. You can find code sample here.
By using FragmentPagerAdapter we can not achieve infinite pager view
functionality.For this I have written my own pager view .Here every
time when you swipe the page it will ask for next page /previous page
by passing current page as reference.So by writing your own logic in
getNextPage(PageView currentPage)/getPreviousPage(PageView
currentPage) methods you can return the respective page until it reaches end.if
reaches end simply return null in those methods.
Here you can fine that sample project.
Let me know if you face any problem while using it.
I am trying to add a ViewPager, but I am am having problems adding new fragments. I followed a tutorial to create it where the on each swipe the SAME fragment was used with only a TextView in the fragment changing changing.
The fragment that works is called MyFragment. ( I don't know why this works and the others don't.
I don't want to use this fragment as I have different fragments that I have already made (that work fine). I want to add for example a fragment called ReminderFragment
I tried adding a switch and case to the getItem() method, but I get an error saying: "Type mismatch: cannot convert from name of fragment to Fragment".
This is the code of my FragmentActivity - it holds the FragmentPagerAdapter inside it (I don't know if this is a good way or not):
// Removed imports, package name
public class PageViewActivity extends FragmentActivity {
MyPageAdapter pageAdapter;
private ViewPager pager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_pager_activity); // Sets the layout to an xml which includes a viewpager
List<Fragment> fragments = getFragments();
pageAdapter = new MyPageAdapter(getSupportFragmentManager(), fragments);
pager = (ViewPager)findViewById(R.id.viewpager);
pager.setAdapter(pageAdapter);
pager.setCurrentItem(1);
pager.setPageTransformer(true, new ZoomOutPageTransformer());
}
#Override
public void onBackPressed() {
if (pager.getCurrentItem() == 1) {
super.onBackPressed();
} else if (pager.getCurrentItem() == 0){
pager.setCurrentItem(pager.getCurrentItem() + 1);
}
else if (pager.getCurrentItem() == 2){
pager.setCurrentItem(pager.getCurrentItem() - 1);
}
}
private List<Fragment> getFragments(){
List<Fragment> fList = new ArrayList<Fragment>();
// I don't know how to change this to work with my fragments
fList.add(MyFragment.newInstance("Page 0")); // MyFragment is the fragment I don't need, but it is the only fragment that works!
fList.add(MyFragment.newInstance("Page 1"));
fList.add(MyFragment.newInstance("Page 2"));
return fList;
}
private class MyPageAdapter extends FragmentPagerAdapter { // Sets what MyPagerAdapter is
private List<Fragment> fragments; // Defines a list of fragments called fragments
public MyPageAdapter(FragmentManager fm, List<Fragment> fragments) { // Sets what is inside the MyPagerAdapter
super(fm);
this.fragments = fragments;
}
#Override
public Fragment getItem(int index) {
// return this.fragments.get(index);
switch (index){
case 0: return new ReminderFragment(); // This is where I get errors
case 1: return new QuickNoteFragment();
}
}
#Override
public int getCount() {
return this.fragments.size();
}
}
}
This is the code of the ReminderFragment. This does not work as I get the error above
// Removed stuff
public class ReminderFragment extends Fragment implements OnClickListener{
public static final String ARG_nOTERACTIVITY_NUMBER = "noter_activity";
// Removed stuff
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View remView = inflater.inflate(R.layout.reminder, container, false);
int i = getArguments().getInt(ARG_nOTERACTIVITY_NUMBER);
String noter_activity = getResources().getStringArray(
R.array.noter_array)[i];
// Removed stuff
getActivity().setTitle(noter_activity); // For navigation drawer(?)
return remView;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()) {
case R.id.***: // Does stuff
case R.id.***:
break;
}
}
}
public static Fragment newInstance() { // Is this necessary
// TODO Auto-generated method stub
ReminderFragment remFrag = new ReminderFragment();
return remFrag;
}
}
I know there are two methods of adding the fragments here - I just trying to show what I have tried :-). I am very confused!
Thank you
Looks that you imported Fragments from the support package in all the class. The import should be android.support.v4.app.Fragment or android.app.Fragment (if you are targeting API level 11) in all the class
I have an Activity with a ViewPager containing multiple fragments. how can i now access a TextView in one of that fragments to change its text from the main activity? I tried multiple ways and they all ended in a NullPointerException.
Activity:
public class SummonerOverview extends SherlockFragmentActivity implements TabListener, OnPageChangeListener {
private ViewPager mPager;
private PagerAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.summoner_overview);
initialize();
}
private void initialize() {
// initialize Pager
mPager = (ViewPager) findViewById(R.id.viewpager);
mAdapter = new PagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mAdapter);
mPager.setCurrentItem(1);
mPager.setOnPageChangeListener(this);
}
}
PagerAdapter:
public class PagerAdapter extends FragmentPagerAdapter {
public PagerAdapter(FragmentManager fm) {
super(fm);
frags = new Fragment[3];
frags[0] = new StatisticsFragment(0);
frags[1] = new RatingsFragment(1);
frags[2] = new HistoryFragment(2);
}
private final int NUM_PAGES = 3;
Fragment[] frags;
#Override
public Fragment getItem(int arg0) {
if (arg0 == 0)
return frags[0];
else if (arg0 == 1)
return frags[1];
else
return frags[2];
}
#Override
public int getCount() {
return NUM_PAGES;
}
}
The Fragment:
public class StatisticsFragment extends SherlockFragment {
public StatisticsFragment(int fragNr) {
this.fragNr = fragNr;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_overview_statistics, container, false);
return v;
}
}
The Textview in the StatisticsFragment is labeled with an id in the fragment_overview_statistics.xml, but when i try
TextView tv = (TextView) findViewById(R.id.id_of_the_textview)
tv.setText("text");
from within the onCreate() Method of the Activity after the initialize() Method, i get an Exception.
Okay, after another hour of googling, i think i solves my own question (although i'm sure there is a better method to solve that)
I now hold all the Data that is displayed by the fragments in the MainActivity and make the Fragmets consume this Data in their onCreateView() Method by using public Methods of the Activity.
In the PagerAdapter, i overwrote getItemPosition() to:
public int getItemPosition(Object object) {
return POSITION_NONE;
}
Now, everytime i update some of the Data, i also call mAdapter.notifyDataSetChanged() which leads into a recreation of all fragments.
It works, although it looks like a poor hack for me. Im sure there must be a better solution because now i have to recreate all fragments for changing one TextView of one Fragment, what is surely not the way it is intended to be done.