I am writing a simple view pager test app that loads a bunch of data from a website and creates pages to display them.
For the most part the displaying is pretty much all works. However, it falls apart when I load a new set of data to display. When I get a new set, it loads all the data perfectly well however, instead of starting from view 0 it starts at a random location. It could start at the end or somewhere in the middle.
I want all the data to load from page 1, like a book. If you load a new book the book should start from page 1 not a random page.
Reloading calls
I've tried using GotCampDetails() which sets the local variable in the class.
viewPager.setCurrentItem(0);
in my fragment but it doesn't work. Also called notifydatasetchanged() on my adapter, still didn't work.
What am I missing?
public class ViewPagerFragment extends Fragment implements WebReadResultsListener {
private ArrayList<HashMap<String, String>> campDetails;
CustomPagerAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.camp_viewpager, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
if (campDetails != null && ! campDetails.isEmpty()) {
ViewPager viewPager = (ViewPager) view.findViewById(R.id.viewpager);
adapter = new CustomPagerAdapter(getActivity(), campDetails, viewPager);
viewPager.setAdapter(adapter);
viewPager.setPageTransformer(true, new ZoomOutPageTransformer());
}
}
#Override
public boolean GotCampDetails(ArrayList<HashMap<String, String>> campDetails) {
this.campDetails = campDetails;
return true;
}
#Override
public boolean GotCampList(ArrayList<HashMap<String, String>> campDetails) {
return false;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
getFragmentManager().putFragment(outState,"fragmentInstanceSaved",getFragmentManager().findFragmentById(R.id.content));
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Handle orientation changes here
}
}
Adapter:
public class CustomPagerAdapter extends PagerAdapter implements ColorChangeListener {
private ArrayList<HashMap<String, String>> campDetails;
private ViewGroup collection;
private Context mContext;
private boolean isRunning = false;
private ColorChangeListener colorChangeListener;
private int color= pink;
private int currentposition;
private ViewPager viewPager;
public CustomPagerAdapter(Context context, final ArrayList<HashMap<String, String>> campDetails, ViewPager viewPager) {
this.campDetails=campDetails;
this.mContext = context;
this.viewPager = viewPager;
colorChangeListener = (ColorChangeListener) mContext;
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int pos) {
currentposition = pos;
if (campDetails.get(currentposition).get("color").equals("green")) {
color = green;
} else {
color = pink;
}
ColorAppBar(color);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
#Override
public Object instantiateItem(ViewGroup collection, final int position) {
LayoutInflater inflater = LayoutInflater.from(mContext);
ViewGroup layout = (ViewGroup) inflater.inflate(R.layout.child_item, collection, false);
if (campDetails.size() <= 0) {
Toast.makeText(mContext, "Error in getting camp details", Toast.LENGTH_SHORT).show();
return null;
}
if (campDetails.get(position).get("description").equals("RD") ) {
layout.setBackgroundColor(mContext.getResources().getColor(green));
} else {
layout.setBackgroundColor(mContext.getResources().getColor(pink));
}
collection.addView(layout);
this.collection = collection;
TextView eName = (TextView) layout.findViewById(R.id.en);
TextView nEName= (TextView) layout.findViewById(R.id.nen);
TextView textView6 = (TextView) layout.findViewById(R.id.textView6);
// ImageView nextImg = (ImageView) groupLayout.get(index).findViewById(R.id.nextImg);
eName.setText(campDetails.get(position).get("name"));
if (position+1 < campDetails.size()) {
nEName.setText(campDetails.get(position+1).get("name"));
textView6.setVisibility(View.VISIBLE);
} else {
nEName.setText("You are DONE!!");
textView6.setVisibility(View.INVISIBLE);
}
return layout;
}
#Override
public void destroyItem(ViewGroup collection, int position, Object view) {
collection.removeView((View) view);
}
#Override
public int getCount() {
return campDetails.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public CharSequence getPageTitle(int position) {
return campDetails.get(position).get("name");
}
#Override
public void ColorAppBar(int color) {
colorChangeListener.ColorAppBar(color);
}
}
I finally managed to get it done.
I had to delay the function call setCurrentItem by a few milliseconds. Race condition? I don't know why this is the case but now it works perfectly.
Here is what I added in case someone else may find it useful:
pager.postDelayed(new Runnable() {
#Override
public void run() {
pager.setCurrentItem(pos);
}
}, 100);
I'm having trouble following the details well enough to pinpoint the problem, but this guy seems to have accomplished what you're trying to do: dynamically add and remove view to viewpager
hope it helps
Related
I am working on an image gallery, where I fetch all the images stored in the Android phone gallery into my application. Please find the link that I followed to develop that image gallery.
Get all images from Gallery into android application Programmatically
I have trying for hours to figure out how to create a full screen slideshow of images. I am able to achieve the full screen image, but it shows the same image all and always, even though the gallery has 3 images. I am using a ViewPagerAdapter to set the image in the adapter for showing the full screen preview. The image slider isn't working and I don't have an idea of why its not working. Please find the source code of what I have tried so far.
Model_images.java
public class Model_images{
String str_folder;
ArrayList<String> al_imagepath;
public String getStr_folder() {
return str_folder;
}
public void setStr_folder(String str_folder) {
this.str_folder = str_folder;
}
public ArrayList<String> getAl_imagepath() {
return al_imagepath;
}
public void setAl_imagepath(ArrayList<String> al_imagepath) {
this.al_imagepath = al_imagepath;
}
}
I followed the same exact tutorial, where I have given a link to the original source code. Even though I have given a link, I'm posting the source code of the ViewPager I tried.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gallery);
ButterKnife.bind(this);
setSupportActionBar(toolbar);
gridView = (GridView)findViewById(R.id.gv_folder);
int_position = getIntent().getIntExtra("value", 0);
adapter = new GridViewAdapter(this, GalleryFragment.al_images,int_position);
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Bundle bundle = new Bundle();
bundle.putInt("position", int_position);
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
SlideshowDialogFragment newFragment = SlideshowDialogFragment.newInstance();
newFragment.setArguments(bundle);
newFragment.show(ft, "slideshow");
}
});
}
Here is the SlideshowFragmentDialog to show the images in a slideview.
SLideShowFragmentDialog.java
public class SlideshowDialogFragment extends DialogFragment {
private String TAG = SlideshowDialogFragment.class.getSimpleName();
private ViewPager viewPager;
private MyViewPagerAdapter myViewPagerAdapter;
private int selectedPosition = 0;
static SlideshowDialogFragment newInstance() {
SlideshowDialogFragment frag = new SlideshowDialogFragment();
return frag;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_image_slider, container, false);
viewPager = (ViewPager) v.findViewById(R.id.viewpager);
//images = (ArrayList<Image>) getArguments().getSerializable("images");
selectedPosition = getArguments().getInt("position");
myViewPagerAdapter = new MyViewPagerAdapter();
viewPager.setAdapter(myViewPagerAdapter);
viewPager.addOnPageChangeListener(viewPagerPageChangeListener);
setCurrentItem(selectedPosition);
return v;
}
private void setCurrentItem(int position) {
viewPager.setCurrentItem(position, false);
displayMetaInfo(selectedPosition);
}
// page change listener
ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
displayMetaInfo(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
};
private void displayMetaInfo(int position) {
Model_images imagePath = GalleryFragment.al_images.get(position);
Toast.makeText(getContext(), imagePath.toString(), Toast.LENGTH_SHORT).show();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(android.support.v4.app.DialogFragment.STYLE_NORMAL, android.R.style.Theme_Black_NoTitleBar_Fullscreen);
}
// adapter
public class MyViewPagerAdapter extends PagerAdapter {
private LayoutInflater layoutInflater;
public MyViewPagerAdapter() {
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.activity_full_screen, container, false);
ImageView imageViewPreview = (ImageView) view.findViewById(R.id.fullScreenImageView);
Model_images image = GalleryFragment.al_images.get(position);
Glide.with(getContext()).load(image.getAl_imagepath().get(position))
.thumbnail(0.5f)
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
.into(imageViewPreview);
container.addView(view);
return view;
}
#Override
public int getCount() {
return GalleryFragment.al_images.size();
}
#Override
public boolean isViewFromObject(View view, Object obj) {
return view == ((View) obj);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
}
I am not posting the source code for the MainActivity and the Adapter classes, since I have given a link to the project directly. I followed the exact same link. If you still want me to post the source codes, I can edit the question and post the missing stuffs. I don't wanna make this post big with all the code base.
Thanks in advance. Any help is appreciated. Please help me on how to achieve full screen slideshow of images.
I have been working on an app to take the blog feed and parse and display it in the app using the Recycler and Card View. I got to the point of adding sliding tabs to display articles in each of the categories in the site in separate tabs. I parse the feed using the category URL and am able to display it using the same Recycler view adapter.
Here comes the problem, as I swipe through the tabs quickly, the content doesn't load in some cases. In some cases, I get articles from one category displayed in another category's tab.
Below is the code for my Tabs fragment:
public class TabsFragment extends Fragment {
ViewPager mViewPager;
ViewPagerAdapter mAdapter;
SlidingTabLayout mSlidingTabLayout;
CharSequence Titles[] = {"Home", "Events", "Category", "Bookmarks", "News"};
int NoOfTabs = 5;
private ProgressBar mProgressBar;
private RecyclerView mRecyclerView;
private MyRecyclerViewAdapter myRecyclerViewAdapter;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_tabs, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
mAdapter = new ViewPagerAdapter(Titles, NoOfTabs);
mProgressBar = (ProgressBar) view.findViewById(R.id.loading_spinner);
mViewPager = (ViewPager) view.findViewById(R.id.pager);
mViewPager.setAdapter(mAdapter);
mSlidingTabLayout = (SlidingTabLayout) view.findViewById(R.id.tabs);
mSlidingTabLayout.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.secondaryBackgroundColor);
}
#Override
public int getDividerColor(int position) {
return getResources().getColor(R.color.secondaryBackgroundColor);
}
});
mSlidingTabLayout.setViewPager(mViewPager);
}
public class ViewPagerAdapter extends PagerAdapter {
CharSequence mTitles[];
int mNoOfTabs;
public ViewPagerAdapter(CharSequence[] titles, int noOfTabs) {
mTitles = titles;
mNoOfTabs = noOfTabs;
}
public CharSequence getPageTitle(int position) {
return mTitles[position];
}
#Override
public int getCount() {
return mNoOfTabs;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
View view = getActivity().getLayoutInflater().inflate(R.layout.pager_item_articles,
container, false);
container.addView(view);
ProcessArticles processArticles;
processArticles = new ProcessArticles(null, mTitles[position]);
processArticles.execute();
mRecyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity().getApplicationContext()));
myRecyclerViewAdapter = new MyRecyclerViewAdapter(new ArrayList<Article>(),
getActivity().getApplicationContext());
mRecyclerView.setAdapter(myRecyclerViewAdapter);
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return object == view;
}
}
public class ProcessArticles extends GetXmlData {
public ProcessArticles(String searchCriteria, String category) {
super(searchCriteria, category);
}
#Override
public void execute() {
super.execute();
ProcessData processData = new ProcessData();
processData.execute();
}
public class ProcessData extends DownloadXmlData {
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ParseArticles parseArticles = new ParseArticles(getData());
boolean operationStatus = parseArticles.process();
if (operationStatus) {
ArrayList<Article> allArticles = parseArticles.getArticles();
myRecyclerViewAdapter.loadNewData(allArticles);
} else {
Toast.makeText(getActivity().getApplicationContext(), "Error establishing correction.", Toast.LENGTH_SHORT).show();
Log.d("MainActivity", "Error establishing correction.");
}
}
}
}
}
The code for the activity displaying the tabs is:
public class TabsActivity extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_tabs);
activateToolbarWithHomeEnabled();
if (savedInstanceState == null) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
TabsFragment fragment = new TabsFragment();
transaction.replace(R.id.tab_content_frame, fragment);
transaction.commit();
}
}
}
How do I separate the content according to category in the tabs? I have tried to reduce the amount of code, so, I have used the same Recycler adapter. Is there any solution to this problem? Or should I change the method of implementation? I am looking to implement something like the Play Newsstand app.
I need to change the size of all views on toggle. I did it but the
textsize got changed only from 3rd view. The first and second got
unchanged. Please suggest to update all the views.
public class MainActivity extends Activity {
ViewPager viewPager;
public static ArrayList<NewsItem> newslist;
public static PagerAdapter adapter;
public static ProgressDialog progressDialog;
LayoutInflater inflater;
public static float fntSize=30;
private ToggleButton togButton1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
newslist = new ArrayList<NewsItem>();
adapter = new ViewPagerAdapter(getApplicationContext(), newslist);
viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setAdapter(adapter);
addMainButtonListener();
loadNews();
}
public void addMainButtonListener() {
togButton1 = (ToggleButton) findViewById(R.id.toggleButton1);
togButton1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
fntSize=50;
} else {
fntSize=30;
}
}
});
#Override
public boolean onCreateOptionsMenu(Menu menu) {
new MenuInflater(this).inflate(R.menu.activity_main, menu);
return (super.onCreateOptionsMenu(menu));
}
private void loadNews(){
progressDialog= ProgressDialog.show(this,"Progress Dialog Title Text","Process Description Text");
News news = new News(getApplicationContext());
news.execute();
viewPager.setCurrentItem(0);
}
}
And My ViewPager class is
public class ViewPagerAdapter extends PagerAdapter {
// Declare Variables
Context context;
ArrayList<NewsItem> newslist = new ArrayList<NewsItem>();
LayoutInflater inflater;
public TextView txtNewsDesc;
public ViewPagerAdapter(Context context, ArrayList<NewsItem> newslist) {
this.context = context;
this.newslist = newslist;
}
#Override
public int getCount() {
return this.newslist.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((RelativeLayout) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.news_item, container,
false);
txtNewsDesc = (TextView) itemView.findViewById(R.id.news_desc);
NewsItem news = this.newslist.get(position);
txtNewsDesc.setTextSize(MainActivity.fntSize);
txtNewsDesc.setText(news.getDesc());
// Add viewpager_item.xml to ViewPager
Typeface typeFace = Typeface.createFromAsset(context.getAssets(), "fonts/preeti.ttf");
txtNewsDesc.setTypeface(typeFace);
((ViewPager) container).addView(itemView);
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
// Remove viewpager_item.xml from ViewPager
((ViewPager) container).removeView((RelativeLayout) object);
}
}
I know the first is not changed since it is not reloaded but what about 2nd view? Please help to change the text size of all the views on toggle button click.
The ViewPager creates and retains another page beside the current one and that demonstrates why the second stay the same.
To achieve what you want you need to update the size manually when the toggle button clicked, you can keep a reference to the current view in the ViewPagerAdapter and create a method to return that view as follow
public TextView getCurrentView(){
return txtNewsDesc;
}
Then in addMainButtonListener method get the current view using the method you have created and update the text size
togButton1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
if (isChecked) {
fntSize=50;
} else {
fntSize=30;
}
((ViewPagerAdapter)viewPager).getCurrentView().setTextSize(fntSize);
}
You should use
public int getItemPosition(Object object) {
return POSITION_NONE;
}
use setTag() in instantiateItem() and instead of called notifyDataSetChanged() use findViewWithTag() and update tour text size.
For see this and in this thread https://stackoverflow.com/a/8024557
i found solution
crerate interface RefreshFragment
public interface RefreshFragment{void refresh();}
in the fragment which is pager item implement RefreshFragment
and at the class where you create the pager adapter do the folowing
circlePageIndicator.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
((RefreshFragment) pagerAdapter.getItem(position)).refresh();
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
i hope this is your solution
I have a FragmentActivity that uses a ViewPager to flip left and right through pages of data (two ListFragments).
public class StopsActivity extends FragmentActivity {
private ViewPager mViewPager;
private PagerTabStrip mPagerTabStrip;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stops);
mPagerTabStrip =(PagerTabStrip)findViewById(R.id.pager_header);
mViewPager = (ViewPager)findViewById(R.id.pager);
mPagerTabStrip.setDrawFullUnderline(true);
mPagerTabStrip.setTabIndicatorColorResource(R.color.pagerTabStrip);
mViewPager.setAdapter(new StopsAdapter(getSupportFragmentManager()));
mViewPager.setCurrentItem(0);
}
private class StopsAdapter extends FragmentPagerAdapter {
public StopsAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return StopsFragment.newInstance(routename, Stop.FORWARD);
case 1:
return StopsFragment.newInstance(routename, Stop.BACKWARD);
}
return null;
}
#Override
public int getCount() { return 2;}
#Override
public CharSequence getPageTitle(int position) { /* implementation ... */}
}
}
Everything runs ok, but I think that the instantation of the second StopFragment invalidate the data of the first one when getItem is called.
public class StopsFragment extends ListFragment {
private StopsAdapter mStopsAdapter;
private ListView mListView;
private String routename;
private int direction;
public static StopsFragment newInstance(String routename, int direction) {
StopsFragment stopsFragment = new StopsFragment();
// Supply arguments
Bundle args = new Bundle();
args.putString("routename", routename);
args.putInt("direction", direction);
stopsFragment.setArguments(args);
return stopsFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Setup the adapter
ArrayList<Stop> stops = ...
mStopsAdapter = new StopsAdapter(getActivity(), stops);
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle inState) {
View rootView = inflater.inflate(R.layout.fragment_stops, container, false);
// Attach the adapter
mListView = (ListView) rootView.findViewById(android.R.id.list);
mListView.setAdapter(mStopsAdapter);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
The page "IDA" corresponds to StopFragment with argument Stop.FORWARD and the page "VUELTA" corresponds the StopFragment with argument Stop.BACKWARD. As you can see in the images below, just one of them (the last one instantiate) is populated:
What I'm doing wrong?
EDIT
This is StopsAdapter
class StopsAdapter extends BaseAdapter {
private ArrayList<Stop> stops;
private LayoutInflater inflater;
public StopsAdapter(Context context, ArrayList<Stop> stops) {
this.stops = stops;
this.inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return stops.size();
}
#Override
public Object getItem(int position) {
return stops.get(position);
}
#Override
public long getItemId(int position) {
return (long)position;
}
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.item_stop, parent, false);
}
TextView name = (TextView)convertView.findViewById(R.id.tvStopName);
TextView description = (TextView)convertView.findViewById(R.id.tvStopDescription);
Stop stop = (Stop)getItem(position);
name.setText(stop.name);
if (stop.info != null) {
description.setText(stop.info);
}
return convertView;
}
}
Ok, my fault. The code that was giving me problems is the only that I haven't posted (ArrayList<Stop> stops = ...). The code about Fragments and ViewPager works correctly.
Yesterday, I posted a question about the PagerAdapter and how to achieve it when using database. I managed to sorted it out, however, I do not want the viewpager to swipe/scroll left I want the opposite (swipe to right). The following is my code:
public class ScrollViewTest6 extends ActionBarAppActivity {
private ViewPager awesomePager;
private static int NUM_AWESOME_VIEWS;
private Context cxt;
private AwesomePagerAdapter awesomeAdapter;
TextView tv;
int _id;
int row_numbers;
int row_position;
private DataAdapter mySQLiteAdapter;
private Cursor cursor;
/** Called when the activity is first created. */
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
cxt = this;
awesomeAdapter = new AwesomePagerAdapter(awesomeAdapter);
awesomePager = (ViewPager) findViewById(R.id.awesomepager);
awesomePager.setAdapter(awesomeAdapter);
mySQLiteAdapter = new DataAdapter(this);
mySQLiteAdapter.createDatabase();
mySQLiteAdapter.open();
Bundle extras = getIntent().getExtras();
if (extras == null) {
return;
}
_id = extras.getInt("id");
row_numbers = extras.getInt("row_num");
row_position = extras.getInt("row_pos");
NUM_AWESOME_VIEWS = row_numbers;
awesomePager.setCurrentItem(row_position);
cursor = mySQLiteAdapter.get_AllColumns();
this.startManagingCursor(cursor);
this.awesomePager.setOnPageChangeListener(new ViewPager.OnPageChangeListener()
{
#Override
public void onPageScrollStateChanged(int arg0) {
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels){
}
#Override
public void onPageSelected(int position){
}
});
}
private class AwesomePagerAdapter extends PagerAdapter{
public AwesomePagerAdapter(PagerAdapter fm) {
}
#Override
public int getCount() {
return NUM_AWESOME_VIEWS;
}
#Override
public int getItemPosition(Object object) {return POSITION_NONE;}
#Override
public Object instantiateItem(ViewGroup collection, int position) {
LayoutInflater inflater = (LayoutInflater)cxt.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.mylayout, null);
TextView Title = (TextView)layout.findViewById(R.id.title);
if (cursor != null ) {
if (cursor.moveToPosition(position)) {
//do {
//cursor.moveToPosition(position);
String text = cursor.getString(
cursor.getColumnIndexOrThrow(DataAdapter.KEY_Title));
Title.setText(text);
}
}
((ViewPager) collection).addView(layout,0);
return layout;
}
#Override
public void destroyItem(View collection, int position, Object view) {
((ViewPager) collection).removeView((View) view);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view==((View)object);
}
#Override
public void finishUpdate(View arg0) {
}
#Override
public void restoreState(Parcelable arg0, ClassLoader arg1) {
}
#Override
public Parcelable saveState() {
return null;
}
#Override
public void startUpdate(View arg0) {
}
}
}
I know some people suggest using
setCurrentItem(int); //Last page
But that conflicts with the listview order.
e.g. Listview:
1
2
3
when we use the line above it shows 1 <- 2 <- 3 (starting from 3)
and I want 3 <- 2 <- 1 (starting from 1)
I face this issue and I resolve with this library
use it and your pagination will work right to left perfectly
it work same as ViewPager
https://github.com/diego-gomez-olvera/RtlViewPager
<com.booking.rtlviewpager.RtlViewPager
android:id="#+id/arabicViewPager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
arabicViewPager = (ViewPager) findViewById(R.id.arabicViewPager);
adapterViewPager = new Adpt_fragmentPageAdapter(getSupportFragmentManager());
arabicViewPager.setAdapter(adapterViewPager);
tabLayout = (TabLayout) findViewById(R.id.sliding_tabs);
tabLayout.setupWithViewPager(arabicViewPager);
Thanks to AleksG
Here is what he suggested to do which works for the required purpose, so add the following line to the list:
setCurrentItem(count - 1)
Then in the cursor you'll need to set up the list order in the cursor "_desc"
Thanks again.