Android Not able to share correct text from viewpager - android

I am trying to share the text that i am showing on viewpager on a button click but it's sending the text from the next page. Like on the first page of viewpager its showing '0' and when I am sharing it to whats app or sms, its sending the text '1' i.e next text from string array.
Here is my code.
SampleFragmant.java
public class SampleFragmant extends Fragment {
ViewPager viewPager;
SampleAdapter adapter;
ImageView shareButton, saveButton;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.sample,
container, false);
viewPager = (ViewPager) rootView
.findViewById(R.id.view_pager);
shareButton = (ImageView) rootView.findViewById(R.id.shareButton);
shareButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent sharingIntent = new Intent(
android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBody = adapter.textposition;
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
"Test Application:");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT,
shareBody);
startActivity(Intent.createChooser(sharingIntent, "Share via"));
}
});
adapter = new SampleAdapter(getActivity());
viewPager.setAdapter(adapter);
return rootView;
}
}
SampleAdapter.java
public class SampleAdapter extends PagerAdapter {
Context context;
public String textposition;
private String[] textToDisplay = new String[] {
"0","1","2","3","4","5","6"};
#Override
public int getCount() {
// TODO Auto-generated method stub
return textToDisplay.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
// TODO Auto-generated method stub
return view == ((TextView) object);
}
#Override
public Object instantiateItem(View container, int position) {
// TODO Auto-generated method stub
TextView textView = new TextView(context);
textView.setText(textToDisplay[position]);
textposition= textToDisplay[position];
textView.setTextSize(16);
textView.setTypeface(null, Typeface.BOLD_ITALIC);
textView.setGravity(Gravity.CENTER);
((ViewPager) container).addView(textView, 0);
return textView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((TextView) object);
}
}

By default ViewPager creates several views at once. For instance, if a view with position 5 is shown to user, it will create views with positions 4, 5 and 6. This is needed for smooth transition animations and controlled by setOffscreenPageLimit(int limit) (by default limit is 1). So, it will instantiate views for these positions by invoking instantiateItem method. And that's why it's incorrect to assume that the position you get in instantiateItem is the position of a view that is shown to user.
Instead of that you should use onPageSelected(int position) of ViewPager.OnPageChangeListener to determine a position of current view.

Related

How to implement Listview Horizondally in carousel?

Is it possible to create a carousel in android which contains set of images which is horizontally aligned in list view . And also i want to highlight one image item when it is clicked.
Please use RecyclerView instead of using ListView. Check out this code - Carousel. Use RecyclerView as a root view with a LinearLayoutManager.HORIZONTAL as a LayoutManager.
Take view Pager inside in layout
<android.support.v4.view.ViewPager
android:id="#+id/viewPager"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
in your activty
public class Event_Image_Slider extends Activity {
ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event__image__slider);
viewPager = (ViewPager) findViewById(R.id.viewPager);
CustomAdapter adapter = new CustomAdapter(Event_Image_Slider.this);
viewPager.setAdapter(adapter);
}
}
Your Custom adpter code ,before it in your activty declare ArrayList imagepathArray =new ArrayList();
public class CustomAdapter extends PagerAdapter{
Context context;
public CustomAdapter(Context context){
this.context = context;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
// TODO Auto-generated method stub
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
View viewItem = inflater.inflate(R.layout.image_item, container, false);
ImageView imageView = (ImageView) viewItem.findViewById(R.id.imageView10);
Glide.with(context).load(yourActivty.imagepathArray.get(position)).into(imageView);
((ViewPager)container).addView(viewItem);
return viewItem;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return yourActivty.imagepathArray.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
// TODO Auto-generated method stub
return view == ((View)object);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
// TODO Auto-generated method stub
((ViewPager) container).removeView((View) object);
}}
You can use this github library for carousel functionality in your project here is the link of carouselview library.
App level Gradle file (not project level gradle):
compile 'com.synnapps:carouselview:0.0.9'
Include following code in your layout:
<com.synnapps.carouselview.CarouselView
android:id="#+id/carouselView"
android:layout_width="match_parent"
android:layout_height="200dp"
app:fillColor="#FFFFFFFF"
app:pageColor="#00000000"
app:radius="6dp"
app:slideInterval="3000"
app:strokeColor="#FF777777"
app:strokeWidth="1dp"/>
Include following code in your activity
public class SampleCarouselViewActivity extends AppCompatActivity {
CarouselView carouselView;
int[] sampleImages = {R.drawable.image_1, R.drawable.image_2, R.drawable.image_3, R.drawable.image_4, R.drawable.image_5};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sample_carousel_view);
carouselView = (CarouselView) findViewById(R.id.carouselView);
carouselView.setPageCount(sampleImages.length);
carouselView.setImageListener(imageListener);
}
ImageListener imageListener = new ImageListener() {
#Override
public void setImageForPosition(int position, ImageView imageView) {
imageView.setImageResource(sampleImages[position]);
}
};
}
Also you can explore it extra supported xml Attributes on given link.

Cannot update views on left and right side of view pager

I have used viewpager which displays view with an image and radiobutton below. Each swipe screen is not a fragment, they are layouts which just swipe the same view with different imageview. The problem is that, I am unable to deselect the radio button which is in left and right side of the current view after i select the radio button of the current screen. If I return POSITION_NONE in getItemPosition(), it refresh the screen and radio button also deselected but the view is flickered. If i am able to call instantiateItem(), my problem is solved . But this method is called only when view is destroyed based on the setOffsetScreenPageLimit(). How can I achieved such requirements, if view pager cannot help?
Fragment:
public class AnswerImageDialogFragment extends DialogFragment implements ViewPager.OnPageChangeListener {
//member declaration
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strQuestion = null;
View rootView = inflater.inflate(R.layout.activity_viewpager_demo, container,
false);
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
intro_images = (ViewPager) rootView.findViewById(R.id.pager_introduction);
pager_indicator = (LinearLayout) rootView.findViewById(R.id.viewPagerCountDots);
//do some stuff
//set the adapter
mAdapter = new ViewPagerAdapter(getContext(), map);
intro_images.setAdapter(mAdapter);
intro_images.setCurrentItem(clickPosition);
intro_images.setOnPageChangeListener(this);
setUiPageViewController();
bus = EventBus.getDefault();
bus.register(this);
return rootView;
}
//other method
}
PagerAdapter:
public class ViewPagerAdapter extends PagerAdapter {
// member declaration
public ViewPagerAdapter(Context mContext, HashMap<String, Object> map) {
//other initialization
}
#Override
public int getCount() {
return optionImages.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((LinearLayout) object);
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
View itemView = LayoutInflater.from(mContext).inflate(R.layout.pager_item, container, false);
final ImageView ivOption = (ImageView) itemView.findViewById(R.id.answerId); // this is used as radio button in this case
/*The code snippet is to select the answer option based on whether answer is choosen or not.
If choosen, select as default in the pop up answer.
*/
if (null != ans) {
Iterator iterator = ans.iterator();
if (ans.size() > 0) {
int value = (int) iterator.next();
if (value == position) {
ivOption.setImageResource(R.drawable.ic_radio_button_tick);
} else {
ivOption.setImageResource(R.drawable.ic_radio_button_nontick);
}
}
}
p = position;
/*The code snippet is to change the answer value based on the user selection.
This means if user choosen another answer then clear the earlier choosen answer
*/
ivOption.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do stuff
}
});
txtQuestion.setText(question);
txtOption.setText(optionsList.get(position));
imageView.setParseFile(optionImages.get(position));
imageView.loadInBackground();
container.addView(itemView);
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
LinearLayout ll = (LinearLayout) object;
/*RelativeLayout ivOption = (RelativeLayout) ll.getChildAt(2);
ImageView iv = (ImageView) ivOption.getChildAt(1);
iv.setImageResource(R.drawable.ic_radio_button_tick);*/
container.removeView(ll);
}
#Override
public int getItemPosition(Object object) {
return super.getItemPosition(object);
}
public void refresh(ArrayList object) {
this.object = new ArrayList();
this.object.addAll(object);
this.notifyDataSetChanged();
}

Android Weird Error : Fragement Dosen't Recreats The View

HERE IS THE VIDEO:
https://www.youtube.com/watch?v=eush2bY0XlQ&feature=youtu.be&hd=1
So here is the plot :
1) I have a navigation drawer.
2) By Clicking on one of the list item a tab layout (fragment) is inflated .
3) So I get a tab layout (with 6 tabs) working besides navigation drawer i.e navigation drawer and tab_layout can be used simultaneously.
4) Content of every tab is a Different fragement.
Problem :
When I launch the application and click the list-item with the tab fragment the content of the tab_fragment is inflated normally.
But when i click it again all the content of the first and second tab dissappear.
And reappear only when when i swipe till the third tab and swipe back again .
In simple words ,
On Calling the static new Instance method of Tab_Fragment for the first time is works fine .
On Calling it again the content of the first and second tab disappear and reappear
only when I swipe till the 3rd tab and come back.
I know it sounds weird.
Code:
My Tab_Fragment To Create it I call its New Instance From MainActivity.
public class Tab_Activity extends Fragment {
private final Handler handler = new Handler();
public PagerSlidingTabStrip tabs;
private ViewPager pager;
private MyPagerAdapter adapter;
public final static String TAG = Tab_Activity.class.getSimpleName();
public Tab_Activity() {
// TODO Auto-generated constructor stub
}
public static Tab_Activity newInstance() {
return new Tab_Activity();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.tab_layout, container, false);
}
#Override
public void onViewCreated(View v, Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onViewCreated(v, savedInstanceState);
tabs = (PagerSlidingTabStrip) v.findViewById(R.id.tabs);
pager = (ViewPager) v.findViewById(R.id.pager);
adapter = new MyPagerAdapter(getActivity().getSupportFragmentManager());
pager.setAdapter(adapter);
final int pageMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources()
.getDisplayMetrics());
pager.setPageMargin(pageMargin);
tabs.setViewPager(pager);
tabs.setIndicatorColorResource(R.color.grey);
tabs.setTextColorResource(R.color.black);
}
public class MyPagerAdapter extends FragmentPagerAdapter {
private final String[] TITLES = { " ELECTRONICS ", " IT ", " COMPUTER "," EXTC ", "INSTRUMENTATION"," MCA " };
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public CharSequence getPageTitle(int position) {
return TITLES[position];
}
#Override
public int getCount() {
return TITLES.length;
}
#Override
public Fragment getItem(int position) {
return Courses.newInstance(position);
}
}
}
The Courses Fragment :
public class Courses extends Fragment {
LinearLayout ll ;
private static final String ARG_POSITION = "position";
public static PagerSlidingTabStrip tab ;
private int position;
public static Courses newInstance(int position) {
Courses f = new Courses();
Bundle b = new Bundle();
b.putInt(ARG_POSITION, position);
f.setArguments(b);
return f;
}
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
position = getArguments().getInt(ARG_POSITION);
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.dept_main,container,false);
}
#Override
public void onViewCreated(View v, Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onViewCreated(v, savedInstanceState);
// generate ID's :
TextView h_name = (TextView) v.findViewById(R.id.tv_dept_name);
TextView f_info = (TextView) v.findViewById(R.id.tv_dept_info);
TextView h_vision = (TextView) v.findViewById(R.id.header_vision);
TextView f_vision = (TextView) v.findViewById(R.id.footer_vision);
TextView h_mission = (TextView) v.findViewById(R.id.header_mission);
TextView f_mission = (TextView) v.findViewById(R.id.footer_mission);
TextView h_eoe = (TextView) v.findViewById(R.id.header_EOE);
TextView f_eoe = (TextView) v.findViewById(R.id.footer_EOE);
TextView h_intake = (TextView) v.findViewById(R.id.header_intake);
TextView f_intake = (TextView) v.findViewById(R.id.footer_intake);
h_intake.setText(R.string.h_intake);
h_mission.setText(R.string.h_mission);
h_vision.setText(R.string.h_vision);
h_eoe.setText(R.string.h_eoe);
switch(position){
case 0 :
//Electronics
h_name.setText("Electronics");
f_info.setText(R.string.ug_course);
f_vision.setText(R.string.v_etrx);
f_mission.setText(R.string.m_etrx);
f_eoe.setText("1984");
f_intake.setText(R.string.intake_etrx);
break ;
case 1 :
h_name.setText("Information Technology");
f_info.setText(R.string.ug_course);
f_vision.setText(R.string.v_it);
f_mission.setText(R.string.m_it);
f_eoe.setText("1984");
f_intake.setText(R.string.intake_it);
break ;
case 2 :
h_name.setText("Computer Science");
f_info.setText(R.string.ug_course);
f_vision.setText(R.string.v_coms);
f_mission.setText(R.string.m_coms);
f_eoe.setText("1984");
f_intake.setText(R.string.intake_coms);
break ;
case 3 :
h_name.setText("Electronics And Telecommunication");
f_info.setText(R.string.ug_course);
f_vision.setText(R.string.v_extc);
f_mission.setText(R.string.m_extc);
f_eoe.setText("1984");
f_intake.setText(R.string.intake_extc);
break ;
case 4 :
h_name.setText("Instrumentation");
f_info.setText(R.string.ug_course);
f_vision.setText(R.string.v_it);
f_mission.setText(R.string.m_it);
f_eoe.setText("1984");
f_intake.setText(R.string.intake_it);
break ;
case 5 :
h_name.setText("Master of Computer Applications");
f_info.setText("Post Graduation Course.(PG)");
f_vision.setText(R.string.v_mca);
f_mission.setText(R.string.m_mca);
f_eoe.setText("1984");
f_intake.setText(R.string.intake_mca);
break;
}
}
}
(Comment for any clarifications ! )
Found My Answer ==> https://stackoverflow.com/a/12582529/3475933
Only Changed FragmenPagerAdapter to FragmentStatePagerAdapter and eveything worked fine.
Hope it helps .!

Fragment does not refresh its content

In the following code I have set up a fragment that shows 2 ListViews.
When the main activity call the Fragment methods:
prendiListaBest
and
prendiListaWorst
they call notifyDataSetChanged() on the adapters,
therefore the lists should update with the new contents of the ArrayLists.
But this does not happen.
Please any help and suggestion more than welcome
public class WorstBest extends Fragment {
public ListView lvBest;
public ListView lvWorst;
public MyAdapter myAdap;
public MyAdapter myAdap2;
public ArrayList<Stock> best;
public ArrayList<Stock> worst;
public View v;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v= inflater.inflate(R.layout.listaworstbest, container, false);
lvBest= (ListView)v.findViewById(R.id.listbest);
lvWorst=(ListView)v.findViewById(R.id.listworst);;
myAdap= new MyAdapter(best, getActivity());
myAdap2= new MyAdapter(worst, getActivity());
lvBest.setAdapter(myAdap);
lvWorst.setAdapter(myAdap2);
return v;
}
public void prendiListaBest(ArrayList<Stock> al){
Log.e("", "passo per prendilitsa del fragment worstbest");
best=al;
Log.e("", "nel fragment best è" + Integer.toString(best.size()));
myAdap.notifyDataSetChanged();
}
public void prendiListaWorst(ArrayList<Stock> al){
Log.e("", "passo per prendilitsa del fragment worstbest");
worst=al;
Log.e("", "nel fragment worst è" + Integer.toString(worst.size()));
myAdap2.notifyDataSetChanged();
}
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
}
}
This is the code of my custom adapter.
I posted as requested but I apologize because it is really messy:
public class MyAdapter extends BaseAdapter {
ArrayList<Stock> l;
Activity a;
public MyAdapter(ArrayList<Stock> li, Activity ac) {
// TODO Auto-generated constructor stub
l = li;
a=ac;
}
public View getView(int position, View convertView, ViewGroup parent) {
View row=convertView;
if (row==null) {
LayoutInflater inflater=a.getLayoutInflater();
row=inflater.inflate(R.layout.row, parent, false);
}
TextView tw=(TextView)row.findViewById(R.id.textView1);
String st=l.get(position).simbolo;
String st1=st;
String st2=st;
String st3=st;
String st4=st;
String st5=st;
String st6=st;
String st7=st;
String st8=st;
st8=st;
if(st.length()<=7){st1=st.concat(" ");st2=st1;st3=st1;st4=st1;st5=st1;st6=st1;st7=st1;st8=st1;}
if(st1.length()<=7){st2=st1.concat(" ");st3=st2;st4=st2;st5=st2;st6=st2;st7=st2;st8=st2;}
if(st2.length()<=7){st3=st2.concat(" ");st4=st3;st5=st3;st6=st3;st7=st3;st8=st3;}
if(st3.length()<=7){st4=st3.concat(" ");st5=st4;st6=st4;st7=st4;st8=st4;}
if(st4.length()<=7){st5=st4.concat(" ");st6=st5;st7=st5;st8=st5;}
if(st5.length()<=7){st6=st5.concat(" ");st7=st6;st8=st6;}
if(st6.length()<=7){st7=st6.concat(" ");st8=st7;}
if(st7.length()<=7){st8=st7.concat(" ");}
tw.setText(st8);
String allora=(String) tw.getText();
TextView tw2=(TextView)row.findViewById(R.id.nome);
///aggiungiamo numero minimo caratteri
tw2.setText((l.get(position).nome));
///
TextView tw3=(TextView)row.findViewById(R.id.prezzo);
tw3.setText((l.get(position).prezzo));
TextView tw4=(TextView)row.findViewById(R.id.cambiamento);
tw4.setText((l.get(position).cambiamento).concat(" %"));
try {
double value = Double.parseDouble(l.get(position).cambiamento);
if(value<0)tw4.setTextColor(Color.RED);
if(value>0)tw4.setTextColor(Color.GREEN);
TextView tw5=(TextView)row.findViewById(R.id.freccia);
if(value<0)tw5.setText("▼");
if(value>0)tw5.setText("▲");
if(value<0)tw5.setTextColor(Color.RED);
if(value>0)tw5.setTextColor(Color.GREEN);
} catch (Exception exc) {}
return row;
}
public int getCount() {
// TODO Auto-generated method stub
return l .size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return l .get(position);
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
}
EDIT EDIT EDIT EDIT EDIT EDIT EDIT EDIT EDIT EDIT EDIT EDIT EDIT EDIT EDIT EDIT EDIT *EDIT EDIT EDIT EDIT EDIT EDIT EDIT EDIT EDIT EDIT EDIT EDIT EDIT EDIT EDIT EDIT EDIT *
Thank you very much, the answer makes perfectly sense.**
But I do not understand why the same Adapter works fine with the following fragment; I explain:
the following "listafragment" fragment has a similar logic, it uses the
prendiLista
method to retrieve the latest version of the
ListArray lt
exactly the same way it is done in the previous "WorstBest" fragment.
But in this case when
public void prendiLista(ArrayList<Stock> al){
lt=al;
myAdap.notifyDataSetChanged();
}
the view is updated !!!
Please what is the difference??? :-)
IN MY UNDERSTANDING THE CALL TO notifyDataSetChanged() WAS ENOUGH TO UPDATE THE VIEW !!
Thanks a lot anyway! (I will accept answer tomorrow morning).
public class listafragment extends Fragment {
public ListView lv;
public MyAdapter myAdap;
public ArrayList<Stock> lt;
public View v;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v= inflater.inflate(R.layout.lista, container, false);
lv= (ListView) v.findViewById(android.R.id.list);
if(lv==null){Log.e("","nel fragment la lista è nulla");}
if(lv!=null){Log.e("","nel fragment la lista NON è nulla");}
myAdap= new MyAdapter(lt, getActivity());
lv.setAdapter(myAdap);
return v;
}
public void prendiLista(ArrayList<Stock> al){
Log.e("", "passo per prendilitsa del fragment");
lt=al;
if(myAdap==null){Log.e("","nel prendilista del fragment myadapt è nullo");};
myAdap.notifyDataSetChanged();
}
public void addToFavorites(int pos){
Quotes.addToFavorites(pos);
}
#Override
public void onCreate(Bundle savedInstanceState){
lt=Quotes.dammi();
super.onCreate(savedInstanceState);
}
}
therefore the lists should update with the new contents of the ArrayLists.
Unfortunately no. When your app first runs l and best both reference the same data. You have this set up.
Fragment:
best ---\
|
|--- <the initial data>
Adapter: |
l ------/
But after you call best=al, you have:
Fragment:
best ------- <the new data>
Adapter:
l ---------- <the initial data>
So you never update the reference in your Adapter. Either add a new method to your custom Adapter to change l or use l itself since you didn't declare it as private:
public void prendiListaBest(ArrayList<Stock> al){
myAdap.l=al;
myAdap.notifyDataSetChanged();
}

How to display different text on each page in ViewPager, instantiateItem() confusion

In the CustomPagerAdapter of the ViewPager, in instantiateItem() method I'm trying to create an TextView and then for each page set a different text depending on certain condition. Text is read from a pages Cursor. Here is a code:
#Override
public Object instantiateItem(ViewGroup collection, int position) {
sc = new ScrollView(context);
sc.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
sc.setFillViewport(true);
tv = new TextView(context);
if(position < count) {
tv.setText(pages.getString(1));
pages.moveToPosition(position);
}else {
tv.setText("LOCKED");
}
tv.setTag(TAG_PAGE + position);
tv.setGravity(Gravity.CENTER);
tv.setTextColor(Color.BLACK);
tv.setTextSize(30);
sc.addView(tv);
((ViewPager) collection).addView(sc);
return sc;
}
However ViewPager behaves not as expected. The first and the second page have the same text, rest of the pages has a sign "LOCKED" as expected. When I swipe into the 4th page and come back to the first page then the first page consists of the text that suppose to be in the second page. I also tried to use myViewPager.setOffscreenPageLimit(numberOfPages) however it doesn't help.
I found this answer:
"Inside of instantiateItem, the position parameter is the position that is in need of rendering. It is NOT the position of the currently focused item that the user would see. The pages to the left and right of the currently displayed view need to be pre rendered in memory so that the animations to those screens will be smooth. "
It make sense to me but how then can I correctly display the pages content and then update it if desired? Please advise if there is different way to do it with skipping instantiateItem() method that introduce the mess and confusion into the problem. Thank you.
I have solved this problem by using a different implementation:
// Adapter class
private static class MyFragmentPagerAdapter extends FragmentPagerAdapter {
public MyFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
return PageFragment.newInstance(pages[index]); // Pages is an array of Strings
}
#Override
public int getCount() {
return numberOfPages;
}
}
// PageFragment class
public class PageFragment extends Fragment {
TextView tv;
public static PageFragment newInstance(String page) {
PageFragment pageFragment = new PageFragment();
Bundle bundle = new Bundle();
bundle.putString("pageContent", page);
pageFragment.setArguments(bundle);
return pageFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment, container, false);
tv = (TextView) view.findViewById(R.id.text_view);
tv.setText(getArguments().getString("pageContent"));
return view;
}
}
You can Create ViewPager Object and then set Listener onthis object.
ViewPager myPager = (ViewPager) findViewById(R.id.yourPagerid);
myPager.setAdapter(adapter);
myPager.setCurrentItem(0);
myPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
//You can change textview word according to current page
switch (position) {
case 0:
break;
case 1:
break;
case 2:
break;
}
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// Log.d("check","onPageScrolled");
}
#Override
public void onPageScrollStateChanged(int arg0) {
// Log.d("check","onPageScrollStateChanged");
}
});

Categories

Resources