ListView not visible in ViewPager in custom ViewGroup - android

I have a custom ViewGroup that has a ViewPager as a child. This is because I want to add a static header to the ViewPager and mess with onDraw() to make the header scroll vertically with the ViewPager content. My ViewPager has a ListView as a child. I'm able to create the ListView and the adapter and even set the adapter to the ListView. When I read wallList.getAdapter().getItemAt(0).toString() it returns the data I would expect it to return. But for some reason, I can't see the ListView at all.
The ViewPager still works as intended and the other four pages have arbitrary text for the time being. But the center page which is supposed to contain the ListView shows a blank screen. I can't figure out what's going on, but it sounds similar to a problem I had before here and was able to hack my way to get something acceptable, but wasn't able to answer my original question.
It seems like you can only call setAdapter() in certain places, not only does it have to be on the UI thread (I think) but it seems to have trouble doing it within certain methods, custom or overrided. Here's my custom ViewGroup code.
public class CustomProfilePager extends ViewGroup{
Bitmap coverPhoto, profilePhoto;
Paint coverStyle, profileStyle;
String name;
int coverHeight;
ViewPager pager;
ProfilePagerAdapter pagerAdapter;
ListView wallList;
Context context;
public CustomProfilePager(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
}
#Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
Log.i("CustomPager", "calling onLayout()");
pager.layout(0, coverHeight+240, getWidth(), getHeight());
// for(int i=0; i<getChildCount(); i++){
// getChildAt(i).layout(l, t, r, b);
// }
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
#Override
protected void onDraw(Canvas canvas) {
Log.i("CustomPager", "calling onDraw()");
super.onDraw(canvas);
if(coverPhoto!=null){
canvas.drawBitmap(coverPhoto, 0, 0, coverStyle);
}
}
public void init(String name){
Log.i("CustomPager", "calling init()");
this.name = name;
coverStyle = new Paint();
coverHeight = (int) (getWidth()/2.7);
profileStyle = new Paint();
wallList = new ListView(context);
pagerAdapter = new ProfilePagerAdapter();
pager = new ViewPager(context);
pager.setAdapter(pagerAdapter);
addView(pager);
pager.setCurrentItem(2);
pager.setOffscreenPageLimit(4);
}
public void setCoverPhoto(Bitmap bitmap){
Log.i("CustomPager", "calling setCoverPhoto()");
int initialWidth = bitmap.getWidth();
int initialHeight = bitmap.getHeight();
int finalHeight = (int) (initialWidth/2.7);
int initialYoffset = (int) (initialHeight-finalHeight)/2;
this.coverPhoto = Bitmap.createBitmap(bitmap, 0, initialYoffset, bitmap.getWidth(), finalHeight);
invalidate();
}
public void setProfilePhoto(Bitmap bitmap){
this.profilePhoto = bitmap;
}
public ViewPager getViewPager(){
return pager;
}
public void setWallAdapter(Profile.WallAdapter adapter){
Log.i("CustomPager", "calling setWallAdapter()");
wallList.setAdapter(adapter);
}
public class ProfilePagerAdapter extends PagerAdapter {
#Override
public void destroyItem(ViewGroup collection, int position, Object view) {
((ViewPager) collection).removeView((View) view);
}
#Override
public Object instantiateItem(ViewGroup collection, int position) {
ViewPager parent = (ViewPager) collection;
switch (position) {
case 2: // Wall
wallList.setDividerHeight(0);
parent.addView(wallList);
return wallList;
default:
TextView testText = new TextView(context);
testText.setText(String.valueOf(position) + ": " + name);
testText.setTextSize(46);
testText.setGravity(Gravity.CENTER);
parent.addView(testText);
return testText;
}
}
#Override
public int getCount() {
return 5;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
}
}

I too have experience that, Some of the View in my ViewPager were getting lost. When debug came to know that it contain only 2 (some time even 1) views in ViewPager. But actually there has to be 3 views since i implemented circular viewpager.
After many trial and error method, i commented the removeView line from destoryItem and i was surprise and it was working perfectly.
I am not sure will this solved your problem since the documentation for destroyItem says
Remove a page for the given position. The adapter is responsible for
removing the view from its container, although it only must ensure
this is done by the time it returns from finishUpdate(ViewGroup).
For me, there should always be 3 views in my ViewPager. since it was a circular ViewPager.
public class ProfilePagerAdapter extends PagerAdapter {
#Override
public void destroyItem(ViewGroup collection, int position, Object view) {
}
#Override
public Object instantiateItem(ViewGroup collection, int position) {
ViewPager parent = (ViewPager) collection;
switch (position) {
case 2: // Wall
wallList.setDividerHeight(0);
parent.addView(wallList);
return wallList;
default:
TextView testText = new TextView(context);
testText.setText(String.valueOf(position) + ": " + name);
testText.setTextSize(46);
testText.setGravity(Gravity.CENTER);
parent.addView(testText);
return testText;
}
}
#Override
public int getCount() {
return 5;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
}

There is a chance that you may only really need to call
notifyDataSetChanged()
on the PagerAdapter and the ListView will then be displayed properly.

Have you called setWillNotDrawEnabled(false) on your customViewGroup?
By default ViewGroups dont call the onDraw method, also try implmenting the onDispatchDraw instead of the onDraw method
Android Custom Layout - onDraw() never gets called

The problem wasn't really obvious and I'm not sure exactly what caused it in the first place. All I had to do was sublass FrameLayout instead of ViewGroup and everything works.

Related

How can I find out which image is the current one in a ViewPager?

I'm fairly new to Android programming, and I'm trying to design an app where when I swipe through several images on a ViewPager that takes up some of the screen, other elements of that same activity/screen will change with it without necessarily 'scrolling' horizontally like the ViewPager does. My problem is that I can't find a way to identify which image in the ViewPager is the 'current' one outside of the ViewPager.
I tried to create a getter for grabbing the position from instantiateItem method, but no luck - because I assume it simply creates everything once, not updating it again, so when I swipe nothing will happen. Also, I realize that my dieValue variable doesn't do anything - but it's meant to serve as an example of what I want to accomplish. The dieValue variable would change based on which image was the current one.
CustomSwipeAdapter.java
public class CustomSwipeAdapter extends PagerAdapter {
private Context ctx;
public int[] image_resources = {R.drawable.d20, R.drawable.d8, R.drawable.d6};
public CustomSwipeAdapter(Context ctx) {
this.ctx = ctx;
}
#Override
public int getCount() {
return image_resources.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
LayoutInflater layoutInflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View item_view = layoutInflater.inflate(R.layout.swipe_layout, container, false);
ImageView imageView = (ImageView) item_view.findViewById(R.id.dieImageView);
imageView.setImageResource(image_resources[position]);
TextView textView = (TextView) item_view.findViewById(R.id.dieValueTop);
if (position == 0) { textView.setText(R.string.d20Label); }
if (position == 1) { textView.setText(R.string.d8Label); }
if (position == 2) { textView.setText(R.string.d6Label); }
container.addView(item_view);
return item_view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((LinearLayout) object);
}
}
DiceRollerActivity.java
public class DiceRollerActivity extends Activity implements View.OnClickListener {
ViewPager viewPager;
CustomSwipeAdapter adapter;
private int dieValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dice_roller);
viewPager = (ViewPager) findViewById(R.id.dieViewPager);
adapter = new CustomSwipeAdapter(this);
viewPager.setAdapter(adapter);
Button RollDieButton = (Button) findViewById(R.id.rollDieButton);
RollDieButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.rollDieButton:
Random rand = new Random();
int random = rand.nextInt(dieValue) + 1;
setDieResults(random);
}
}
// Prints the results of the die roll to the results log
private void setDieResults(int random) {
TextView dieResults = (TextView) findViewById(R.id.dieResultsLabel);
if (random == dieValue) {
dieResults.setText(getString(R.string.YouRolledLabel) + random + getString(R.string.criticalHit));
} else if (random == dieValue) {
dieResults.setText(getString(R.string.YouRolledLabel) + random + getString(R.string.criticalMiss));
}else{
dieResults.setText(getString(R.string.YouRolledLabel) + random);
}
}
}
Create a method inside your CustomSwipeAdapter
public int getCurrentImageResource(int currentPosition){
return image_resources[currentPosition];
}
To access to the current image call this method passing current position with viewPager.getCurrentItem() like this
adapter.getCurrentImageResource(viewPager.getCurrentItem());
Hope this helps!
You could use
viewPager.getCurrentItem();
on your DiceRollerActivity.class to get the current position.
Then, to get the image a better approach would be to have the image array on your DiceRollerActivity.class and pass it onto the CustomSwipeAdapter constructor.

ViewPager not showing the right page

I am trying to implement a ViewPager without using Fragments. Let's say, I have an unspecific amount of data stored inside some kind of database which is mapped to specific days. What I am trying to do is to display the data for a specific day on ViewPager pages.
This is what I am currently doing:
#Override
protected void onCreate(Bundle savedInstanceState) {
dataList = (ViewPager) findViewById(R.id.dataList);
dataList.setAdapter(new DataListSlidePagerAdapter());
dataList.setCurrentItem(Integer.MAX_VALUE / 2);
}
private class DataListSlidePagerAdapter extends PagerAdapter {
int lastPosition;
#Override
public Object instantiateItem(ViewGroup collection, int position) {
if (position > lastPosition) {
GregorianCalendar today = Settings.getCurrentDay();
today.add(GregorianCalendar.DATE, 1);
Settings.loadData();
}
else if (position < lastPosition) {
GregorianCalendar today = Settings.getCurrentDay();
today.add(GregorianCalendar.DATE, -1);
Settings.loadData();
}
lastPosition = position;
LinearLayout v = createDataList(Settings.getTodaysData());
collection.addView(v);
return v;
}
#Override
public void destroyItem(ViewGroup collection, int position, Object view) {
((ViewPager) collection).removeView((LinearLayout) view);
}
#Override
public int getCount() {
return Integer.MAX_VALUE;
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == ((View) arg1);
}
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
This actually almost works, but unfortunately, the data for the current day is never shown on the current page, but rather on the next or previous page. My guess would be, that this is because instantiateItem does not necessarily build the view of the current page, but rather of some page which is probably needed to be shown next. createListData(), however, always creates the view of the current day.
Any idea how to fix this and to display the right data on the right pages? You can assume, that there are also functions like Settings.getTomorrowsData() and Settings.getYesterdaysData().

How to set Imageview as an object?

I am working with carousel view. With one layout, I put four images.
And I want to set each image as an each object because I want to set a different method when each image is clicked.
ImageButton product_photo = (ImageButton) l.findViewById(R.id.myoffer_image);
product_photo.setImageResource(R.drawable.myoffers_0);
product_photo.setImageResource(R.drawable.myoffers_1);
product_photo.setImageResource(R.drawable.myoffers_2);
product_photo.setImageResource(R.drawable.myoffers_3);
I tried like the code below..but surely it makes an error..
ImageButton one = product_photo.setImageResource(R.drawable.myoffers_0);
I don't know if my question is clear..but if you reply something to know more clear, I will explain it!
Here is pageadapter class!
public class Myoffers_PagerAdapter extends FragmentPagerAdapter implements
ViewPager.OnPageChangeListener {
private Myoffers_LinearLayout cur = null;
private Myoffers_LinearLayout next = null;
private Myoffers context;
private FragmentManager fm;
private float scale;
public Myoffers_PagerAdapter(Myoffers context, FragmentManager fm) {
super(fm);
this.fm = fm;
this.context = context;
}
#Override
public Fragment getItem(int position)
{
// make the first pager bigger than others
if (position == Myoffers.FIRST_PAGE)
scale = Myoffers.BIG_SCALE;
else
scale = Myoffers.SMALL_SCALE;
position = position % Myoffers.PAGES;
return Myoffers_Fragment.newInstance(context, position, scale);
}
#Override
public int getCount()
{
return Myoffers.PAGES * Myoffers.LOOPS;
}
//#Override
public void onPageScrolled(int position, float positionOffset,
int positionOffsetPixels)
{
if (positionOffset >= 0f && positionOffset <= 1f)
{
cur = getRootView(position);
next = getRootView(position +1);
cur.setScaleBoth(Myoffers.BIG_SCALE
- Myoffers.DIFF_SCALE * positionOffset);
next.setScaleBoth(Myoffers.SMALL_SCALE
+ Myoffers.DIFF_SCALE * positionOffset);
}
}
//#Override
public void onPageSelected(int position) {}
//#Override
public void onPageScrollStateChanged(int state) {}
private Myoffers_LinearLayout getRootView(int position)
{
return (Myoffers_LinearLayout)
fm.findFragmentByTag(this.getFragmentTag(position))
.getView().findViewById(R.id.root);
}
private String getFragmentTag(int position)
{
return "android:switcher:" + context.pager.getId() + ":" + position;
}
}
Main class!
public class Myoffers extends FragmentActivity {
public final static int PAGES = 4;
public final static int LOOPS = 1000;
public final static int FIRST_PAGE = PAGES * LOOPS / 2;
public final static float BIG_SCALE = 1.0f;
public final static float SMALL_SCALE = 0.5f;
public final static float DIFF_SCALE = BIG_SCALE - SMALL_SCALE;
public Myoffers_PagerAdapter adapter;
public ViewPager pager;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myoffers);
pager = (ViewPager) findViewById(R.id.myviewpager);
adapter = new Myoffers_PagerAdapter(this, this.getSupportFragmentManager());
pager.setAdapter(adapter);
pager.setOnPageChangeListener(adapter);
pager.setCurrentItem(FIRST_PAGE);
pager.setOffscreenPageLimit(3);
pager.setPageMargin(-100);
}
}
Fragment code
public class Myoffers_Fragment extends Fragment {
protected static final String TAG = "Philips";
FileOutputStream mOutputStream;
private String id;
public static Fragment newInstance(Myoffers context, int pos, float scale)
{
Bundle b = new Bundle();
b.putInt("pos", pos);
b.putFloat("scale", scale);
return Fragment.instantiate(context, Myoffers_Fragment.class.getName(), b);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (container == null) {
return null;
}
LinearLayout l = (LinearLayout) inflater.inflate(R.layout.mf, container, false);
int pos = this.getArguments().getInt("pos");
TextView tv = (TextView) l.findViewById(R.id.text);
tv.setText("Product " + pos);
/*
* Put images with Hard-Coding
*/
{
ImageButton product_photo = (ImageButton) l.findViewById(R.id.myoffer_image);
product_photo.setImageResource(R.drawable.myoffers_0);
product_photo.setImageResource(R.drawable.myoffers_1);
product_photo.setImageResource(R.drawable.myoffers_2);
product_photo.setImageResource(R.drawable.myoffers_3);
}
Myoffers_LinearLayout root = (Myoffers_LinearLayout) l.findViewById(R.id.root);
float scale = this.getArguments().getFloat("scale");
root.setScaleBoth(scale);
return l;
}
Thanks!
Your question is a little vague, but I will respond to the best of my ability--if I am misunderstanding anything, feel free to let me know and I will edit my answer accordingly.
Since 'carousel' is not part of the android SDK, it is a little difficult to be sure what you need to do (it would help if you showed what class/library you are using for this carousel). However, chances are that it will be using this class or a subclass of it in the implementation: AbsListView
Every listview-based class has some method that is called when an item is clicked (here, it is performItemClick). When it is called, it will in turn call the onItemClick method of the associated AdapterView. The adapter is something that you (or the library you are using) created, filled with your data to be displayed, and attached to the ListView.
By registering an AdapterView.OnClickListener, you can specify what behavior a click on a list item at any given index will cause.
Without more details about your carousel, I cannot provide any more code-specific help. However, if you post more info I would be happy to update my answer!
ImageButton is a class, and you created an object of that type called 'product_photo'. Then you create another called 'one'. The problem is that you tried to assign a method to one rather than create a new ImageButton. Instead you should have
ImageButton one = new ImageButton();
one.setImageResource(R.drawable.myoffers_0);
Whether or not 'one' needs to be something in your layout that you get with findViewById or not (likely you do) is up to your application.

PagerAdapter class instantiateItem getting called twice automatically in onCreate

I am new with viewpager, i want to create view using viewpager, here all the things are dynamic, so i followed this way, My problem is that instantiateItem() is getting called twice oncreate.
Oncreate
{
pager = (ViewPager) findViewById(R.id.panelPager);
adapter = new MyPagerAdapter();
pager.setAdapter(adapter);
}
public class MyPagerAdapter extends PagerAdapter {
#Override
public Object instantiateItem(View collection,int position) {
Log.d("Pos",""+position);
//PagerView = new View(collection.getContext());
LayoutInflater inflater = (LayoutInflater) collection.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
PagerView = inflater.inflate(R.layout.newmainviewpager, null, false);
lvMenu=(ListView)PagerView.findViewById(R.id.lvMenuItem);
imgMainItem=(ImageView)PagerView.findViewById(R.id.imgDisplay);
addMenuItemAdapter.clear();
addMenuItemAdapter.notifyDataSetChanged();
addMenuItemAdapter.notifyDataSetInvalidated();
String str[][] = datasource.GetSubMenuDetailsFromMenuId(MenuIdlst
.get(position).trim());
Log.d("Str", "" + str.length);
SubMnuIdlst.clear();
SubMnuNamelst.clear();
ArabicSubMnulst.clear();
TypeIdlst.clear();
TypeNamelst.clear();
for (int i = 0; i < str.length; i++) {
SubMnuIdlst.add(""+str[i][0]);
SubMnuNamelst.add(""+str[i][2]);
ArabicSubMnulst.add(""+str[i][3]);
Log.d("SubMenuId",""+str[i][0]);
Log.d("SubMenuName",""+str[i][2]);
Log.d("SubMenuNameArabicMenu",""+str[i][3]);
}
String [][]TypeDetails=datasource.GetTypeDetailsFromMenuId(MenuIdlst.get(position));
for (int i = 0; i < TypeDetails.length; i++) {
TypeIdlst.add(TypeDetails[i][0]);
TypeNamelst.add(TypeDetails[i][3]);
Log.d("TypeId",""+TypeDetails[i][0]);
Log.d("TypeName",""+TypeDetails[i][3]);
}
for(int i=0;i<SubMnuIdlst.size();i++)
{
//Pricelst.clear();
for(int j=0;j<TypeIdlst.size();j++)
{
String Price=datasource.getPriceFromSubMenuIdAndTypeId(TypeIdlst.get(j),SubMnuIdlst.get(i));
//Pricelst.add(Price);
Log.d("Adaper",MenuIdlst.get(i)+","+SubMnuIdlst.get(i)+","+SubMnuNamelst.get(i)+","+
TypeIdlst.get(j)+","+TypeNamelst.get(j)+","+Price);
addMenuItemAdapter.add(MenuIdlst.get(i)+","+SubMnuIdlst.get(i)+","+SubMnuNamelst.get(i)+","+
TypeIdlst.get(j)+","+TypeNamelst.get(j)+","+Price);
}
}
byte[] photo =datasource.getImagePathFromSubMenuId(SubMnuIdlst.get(position));
ByteArrayInputStream imageStream = new ByteArrayInputStream(photo);
Bitmap theImage= BitmapFactory.decodeStream(imageStream);
Bitmap bitmapScaled = Bitmap.createScaledBitmap(theImage, 100,80, true);
Drawable drawable = new BitmapDrawable(bitmapScaled);
imgMainItem.setBackgroundDrawable(drawable);
lvMenu.setAdapter(addMenuItemAdapter);
((ViewPager) collection).addView(PagerView, 0);
return PagerView;
}
#Override
public void destroyItem(ViewGroup collection, int position, Object view) {
((ViewPager) view).removeView((View) view);
}
/**
* Determines whether a page View is associated with a specific key object
* as returned by instantiateItem(ViewGroup, int). This method is required
* for a PagerAdapter to function properly.
* #param view Page View to check for association with object
* #param object Object to check for association with view
* #return
*/
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((View) object);
}
/**
* Called when the a change in the shown pages has been completed. At this
* point you must ensure that all of the pages have actually been added or
* removed from the container as appropriate.
* #param arg0 The containing View which is displaying this adapter's
* page views.
*/
#Override
public void finishUpdate(ViewGroup arg0) {}
#Override
public void restoreState(Parcelable arg0, ClassLoader arg1) {}
#Override
public Parcelable saveState() {
return null;
}
#Override
public void startUpdate(ViewGroup arg0) {}
#Override
public int getCount() {
// TODO Auto-generated method stub
return MenuIdlst.size();
}
}
It is the behavior to call it twice as view pages make its next view and store it for fast switching from current to next, basically it makes its left and right element for current view so that you can scroll page in any direction, at start page as there is no left page that's why it is called twice only.
You can also change the no of views you want to create and hold for situation but in general and I think minimal(not sure but practically faced some times) is 3
Could it be that your viewpager is nested inside a view group which depends on other views (e.g. LinearLayout with layout_weight set or a RelativeLayout with references to other views in order to calculate its height and/or width)? If so this could be due to multiple layout requests of the parent view since it depends on other views. If this is the cause than try to optimize your layout.
Other way to fix this is overriding the getCount() method defining the number of elements to load inside the pager.
#Override
public int getCount() {
return NUMBER_OF_PAGES;
}

Adding/Removing views for PagerAdapter / ViewPager issue Android

I would like to keep a list of 3 views at all times. The app starts at position 1 (out of positions 0,1,2). When someone scrolls to position 0, I would like to remove view 2, and create a view before position 0. This way, it appears to the user, that there are unlimited views. In the same way, when someone scrolls to position 2, I would like to remove the view at position 0 and add one at the end.
However I'm having problems with both adding and removing views. When I get to position 0, nothing changes unless I try scrolling past position 0 (to position -1, i.e. the boundary is hit). At that point, I can see that it is the boundary of my views, but then setCurrentItem(1,false) is triggered and I'm brought back to the middle of the views. When I scroll to position 2 I see that position 2 has been updated. However position 0 and 1 remain the same.
When I scroll to position 2, nothing happens. However if I try and scroll to the boundary, for some reason, position 0 gets updated and setCurrentItem(1,false) is triggered.
I have no idea why its happening like this. Can anyone shed some light on this?
Here is my code:
public class MainActivity extends Activity {
ArrayList<Integer> showThree = new ArrayList<Integer>();
int focusedPage = 0;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showThree.add(0,5); //adding integers 5,6,7 for positions 0,1,2
showThree.add(1,6);
showThree.add(2,7);
final MyPagerAdapter adapter = new MyPagerAdapter(getApplicationContext(),showThree);
final ViewPager myPager = (ViewPager) findViewById(R.id.mypanelpager);
myPager.setAdapter(adapter);
myPager.setCurrentItem(1);
myPager.setOnPageChangeListener(new OnPageChangeListener(){
#Override
public void onPageScrollStateChanged(int state) {
if (state == ViewPager.SCROLL_STATE_IDLE) {
//when position= 0, change the 3 views from 5,6,7 to 4,5,6.
if (focusedPage == 0) {
showThreeMonths.set(0,4);
showThreeMonths.set(1,5);
showThreeMonths.set(2,6);
adapter.notifyDataSetChanged();
adapter.startUpdate(myPager);
}
else if (focusedPage ==2){
//ignore, just testing focusPage=0 for now }
}
//set current page to the middle of the 3 new views, which would be
//the same view at position 0 of the old 3 views.
//Thus user doesn't experience the views changing despite being 3 new views.
myPager.setCurrentItem(1,false);
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
// TODO Auto-generated method stub
}
#Override
public void onPageSelected(int position) {
focusedPage = position;
}
});
}
PagerAdapter
public class MyPagerAdapter extends PagerAdapter {
private ArrayList<Integer> showThreeMonths;
private Context ctx;
public MyPagerAdapter (Context ctx, ArrayList<Integer> showThree){
this.ctx = ctx ;
this.showThree = showThree;
}
#Override
public int getCount() {
return showThree.size();
}
public Object instantiateItem(ViewGroup collection, int position ){
//NewCustomView is a class I made that takes parameters context and an integer and creates a view based on the integer
NewCustomView MyOwnView = new NewCustomView(ctx, showThree.get(position));
View customViewLayout = MyOwnView.newLayout; //part of the class object
collection.addView(customViewLayout);
return customViewLayout;
}
#Override
public void destroyItem(ViewGroup collection, int position, Object arg2) {
((ViewPager) collection).removeView((ViewGroup) arg2);}
#Override
public Parcelable saveState() {
return null;}
#Override
public boolean isViewFromObject(View view, Object arg1) {
return view==arg1;}
#Override
public void startUpdate(ViewGroup collection) {}
#Override
public void finishUpdate(ViewGroup collection) {}
}
The instantiateItem() method creates the 2 view pages in the memory by default. Therefore when you swipe to the second page then 0 page is recreated as it's outside the range of the 2 pages saved in the memory. Please try to use
myViewPager.setOffscreenPageLimit(numberOfPages)
method that receives an integer as a parameter and declares how many pages it should be keeping before recycling them.

Categories

Resources