how to get item number in view pager? - android

how to get current item no in viewpager.
#Override
public Object instantiateItem(ViewGroup paramView, int paramInt) {
int itemno1= getItem(pager.getCurrentItem());
int itemno2= getItem(paramInt);
Toast.makeText(context, "postition"+itemno1, Toast.LENGTH_SHORT).show();
//Toast.makeText(context, "postition"+itemno2, Toast.LENGTH_SHORT).show();
}
but this methods are not working properly.when ever i swipe front and back it gives the wrong item no..

set ViewPager.setOnPageChangeListener on your viewpager.
Some thing like this-
myViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int i, float v, int i2) {
}
#Override
public void onPageSelected(int i) {
// here you will get the position of selected page
}
#Override
public void onPageScrollStateChanged(int i) {
}
});

try like this
ViewPager.getCurrentItem();
or
pageListener = new PageListener();
ViewPager.setOnPageChangeListener(pageListener);
you have to put a page change listener for your viewPager. There is no method on viewPager to get the current page.
private int currentPage;
private static class PageListener extends SimpleOnPageChangeListener{
public void onPageSelected(int position) {
Log.i(TAG, "page selected " + position);
currentPage = position;
}
}

Related

Get Current item ViewPageAdapter Android

Im searching in all internet but I dont find any REAL solution about my problem.
I have a class with a Viewpager. (Class DescripcionRutinas)
private void setupViewPager(ViewPager viewPager) {
adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addNumDias(numDias);
adapter.setDias(dias);
viewPager.setAdapter(adapter);
viewPager.setOffscreenPageLimit(5);
}
And I have a ViewPagerAdapter
class ViewPagerAdapter extends FragmentPagerAdapter {
private int numDias;
private int count = 0;
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
ArrayList<Dia> dias;
#Override
public Fragment getItem(int position) {
OneFragmentSeries fragmento = new OneFragmentSeries();
Dia ex = dias.get(**I NEED CURRENT ITEM HERE**);
nomDia = ex.getNombre();
fragmento.setSeries((ArrayList<Serie>)((ArrayList<Dia>)WorkoutYourself.dameWorkoutYourself().dameRutina(nomRutina).getDias()).get(position).getSeries());
return fragmento;
}
I need the current item position here.
NOTE: ViewPagerAdapter is INSIDE DescripcionRutinas.
Thanks guys!
Try to use yourViewPager.getCurrentItem() it should work to get your visible pager position.
Update
onPageSelected(int currentPage) should do the stuff
dia.setOnPageChangeListener(new OnPageChangeListener() {
public void onPageScrollStateChanged(int arg0) {
}
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
public void onPageSelected(int currentPage) {
//here you get your current position
}
});
Read this documentation
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int positionCurrentPage) {
if(positionCurrentPage == 1){ // if you want the second page, for example
//Your code here
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});

why viewPager addOnPageChangeListener works with tab clicking and break on scrolling pages?

I have a viewPager of four different tabs, i'm using addOnPageChangeListener to manage page scrolling, the following code is trying to get a view from the first fragment when clicking on a button on the fourth fragment, this works fine when i click on tabs and break when i scroll the pages, which i couldn't find a reason why, the exception i get is a java.lang.NullPointerException for the EditTest view error
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float
positionOffset, int positionOffsetPixels) {
if(position == 3){
EditText title = (EditText) findViewById(R.id.title);
Log.d("Hello", title.getText().toString());
}
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
link to gif showing the problem here
i have tried to move this code to onPageSelected and it didn't work, i also tried to get the fragment view using the following code and no luck:
public View getFragmentView(int position) {
String fragmentD = "android:switcher:" + viewPager.getId() + ":" + position;
android.support.v4.app.Fragment fragment =
getSupportFragmentManager().findFragmentByTag(fragmentD);
return fragment.getView();
}
question is why this works with tab clicking and doesn't with scrolling?
You must call it in OnCreate
public class MainActivity extends Activity {
EditText title;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
title = (EditText) findViewById(R.id.title);
}
}
And at public void onPageSelected(int position)
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float
positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
if(position == 3){
Log.d("Hello", title.getText().toString());
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});

HackyView Pager is not showing the correct position

https://github.com/chrisbanes/PhotoView
i am using this library to show some photos in viewpager (HackyViewPager)
it works fine to show the pictures
but when i want to show name of proper photo that is showing it shows the wrong position name...
i'm wondering of this error
mViewPager.setAdapter(new SamplePagerAdapter());
public class SamplePagerAdapter extends PagerAdapter {
final String[][] sDrawables = {{"Chrysanthemum.jpg","0"},{"Desert.jpg","1"},{"Hydrangeas.jpg","2"},{"Jellyfish.jpg","3"}, {"Koala.jpg","4"},{"Lighthouse.jpg","5"},{"Penguins.jpg","6"},{"Tulips.jpg","7"} };
#Override
public int getCount() {
return sDrawables.length;
}
#Override
public View instantiateItem(ViewGroup container,int position) {
PhotoView photoView = new PhotoView(container.getContext());
Log.i("xxx position ",position + " " + sDrawables[position][1]);
tvImageName.setText(sDrawables[position][1]);
Picasso.with(ViewPagerActivity.this)
.load("http://myserver/uploads/" + sDrawables[position][0])
.placeholder(R.drawable.placeholder)
.error(R.drawable.error)
.into(photoView);
container.addView(photoView, LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);
return photoView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
}
would you please help me to find why this work like this?
Finally i found the answer myself
We have to add a listener (setOnPageChangeListener) for HackyViewPager instead of adding code inside the Adapter.
mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
Log.i("xxx position ",position + " " + sDrawables[position][1]);
tvImageName.setText(sDrawables[position][1]);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});

PageViewer: How to get class of adjacent pages?

I use a PageViewer to scroll through two types of fragments.
One of them has an EditText the other multiple buttons.
Upon entering the EditText Fragment I automatically open the softkeyboard. Upon entering the Button Fragment i close it.
This works fine.
The problem is that I have multiple EditText Fragments as direct neighbours to each other.
-> I dont want the keyboard to be closed when transitioning from one EditText Fragment to the next.
For this I somehow need to predict the class to which I am transitioning next.
Is there a way to achieve this?
Note: I close the keyboard in the pageTransform method as soon as a swipe movement occurs.
EDIT
because of an request in the comments here my PagerAdapter:
public class ButtonCollectionPagerAdapter extends FragmentStatePagerAdapter {
public ButtonCollectionPagerAdapter(FragmentManager fm) {
super(fm);
}
private Fragment currentFragment;
#Override
public Fragment getItem(int i) {
Bundle args = new Bundle();
List<MultipleChoiceQuestion> multipleChoiceQuestions = QuestionTexts.getMCQuestionTexts();
List<String> questionTexts = QuestionTexts.getQuestionTexts();
if(i < multipleChoiceQuestions.size()){
String question = multipleChoiceQuestions.get(i).getText();
ArrayList<String> choices = (ArrayList<String>) multipleChoiceQuestions.get(i).getChoices();
currentFragment = ButtonFragment.newInstance(question, choices, i);
} else if(i < (multipleChoiceQuestions.size() + questionTexts.size())){
currentFragment = TextViewFragment.newInstance(questionTexts.get(i - multipleChoiceQuestions.size()), i);
} else {
currentFragment = SendFragment.newInstance(i);
}
return currentFragment;
}
#Override
public int getCount() {
return 23;
}
#Override
public CharSequence getPageTitle(int position) {
return "OBJECT " + (position + 1);
}
#Override
public void setPrimaryItem(ViewGroup container, int position, Object object){
super.setPrimaryItem(container, position, object);
currentFragment = (Fragment) object;
((PagerAdapterUpdateProgress) object).onGettingPrimary(position);
}
public Fragment getCurrentFragment() {
return currentFragment;
}
}
I think the more simple way to do that is to open/close keyboard directly from your fragments. You can determine when your fragment becomes visible by overriding setUserVisibleHint method of your fragment. The code in this method for your EditText Fragment should just show keyboard, and the code for other fragment should hide keyboard.
This is an interesting question.
I believe that you can achieve what you are doing by using ViewPager.OnPageChangeListener listener especially onPageSelected(int position) method in which we could get the position of the currently selected fragment after the swipe animation has finished.
mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
Log.d("ViewPager", "Page selected " + position);
onPageSelectedLogic(position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
// This is because the first fragment doesn't fire the OnPageChangeListener.
onPageSelectedLogic(0);
an this is the implementation of onPageSelectedLogic method
private void onPageSelectedLogic(int position) {
// Check the type of the fragment editable vs button
if(!mPagerAdpater.isFragmentEdiatable(position)) {
// Close the Keyboard
}
}
And this is how you should implement your PagerAdapter
class CustomPagerAdapter extends FragmentStatePagerAdapter {
private SparseBooleanArray fragmentsEditable = new SparseBooleanArray();
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fargment;
// get the fragment
if(some condition) {
// Get an editable fragment
fragmentsEditable.put(position, true);
} else {
fragmentsEditable.put(position, false);
}
return fragment;
}
#Override
public int getCount() {
return NUM_PAGES;
}
public boolean isFragmentEditable(int postion) {
return fragmentsEditable.get(postion);
}
}

How to update views of viewpager on swipe - android

I am using view-pager.In that I have three tabs : 1. History , 2. Main , 3. Map .
I have stopwatch into main activity.When I press the start and then after stop at that time value of the stopwatch add into the sqlite DB. And into history activity I am fetching the value of stopwatch from DB and store into the listview. It's working perfect.
But now I want the update the History activity when I swipe from the Main > History so After press the stop button,I got the last value into listview of history activity.
My question is how can I update the view on swipe the viewpager?
public class SwipeyTabsSampleActivity extends FragmentActivity {
private static final String [] TITLES = {
"HISTORY",
"MAIN",
"MAP"
};
private SwipeyTabs mTabs;
private ViewPager mViewPager;
//Handler handler=new Handler();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_swipeytab);
mViewPager = (ViewPager) findViewById(R.id.viewpager);
mTabs = (SwipeyTabs) findViewById(R.id.swipeytabs);
SwipeyTabsPagerAdapter adapter = new SwipeyTabsPagerAdapter(this,
getSupportFragmentManager());
mViewPager.setAdapter(adapter);
mTabs.setAdapter(adapter);
mViewPager.setOnPageChangeListener(mTabs);
mViewPager.setCurrentItem(1);
mViewPager.setOffscreenPageLimit(3);
}
private class SwipeyTabsPagerAdapter extends FragmentPagerAdapter implements
SwipeyTabsAdapter, ViewPager.OnPageChangeListener {
private final Context mContext;
ViewPager viewpager;
public SwipeyTabsPagerAdapter(Context context, FragmentManager fm, ViewPager mViewPager) {
super(fm);
this.mContext = context;
viewpager = mViewPager;
//viewpager.setAdapter(this);
viewpager.setOnPageChangeListener(this);
}
#Override
public Fragment getItem(int position) {
Fragment f = new Fragment();
switch (position) {
case 0:
f = History.newInstance(position);
break;
case 1:
f = Main.newInstance(position);
break;
case 2:
f = Map.newInstance(position);
break;
}
return f;
}
#Override
public int getCount() {
return TITLES.length;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
ViewPager pager = (ViewPager) container;
View view = (View) object;
pager.removeView(view);
}
public TextView getTab(final int position, SwipeyTabs root) {
TextView view = (TextView) LayoutInflater.from(mContext).inflate(
R.layout.swipey_tab_indicator, root, false);
view.setText(TITLES[position]);
view.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mViewPager.setCurrentItem(position);
}
});
return view;
}
#Override
public void onPageScrollStateChanged(int state) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
// TODO Auto-generated method stub
}
#Override
public void onPageSelected(int positiion) {
// TODO Auto-generated method stub
}
}
}
Add ViewPager OnPageChangeListener:
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
// your code here
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
This will affect the changes from one page to another page in view pager.
OnPageChangeListener pagechangelistener =new OnPageChangeListener() {
#Override
public void onPageSelected(int arg0) {
Logger.logMessage("Called first");
pageAdapter.notifyDataSetChanged();
indicator.setCurrentItem(arg0);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
Logger.logMessage("Called second");
}
#Override
public void onPageScrollStateChanged(int arg0) {
Logger.logMessage("Called third");
}
};
myViewPager.setOnPageChangeListener(pagechangelistener);
Use this in your page adapter.
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
Take one string and add the Getters and setters into your FragmentActivity class.
Like...
String HistoryFragment;
public String getHistoryFragment() {
return HistoryFragment;
}
public void setHistoryFragment(String historyFragment) {
HistoryFragment = historyFragment;
}
Then after we can access another fragment from our current fragment by calling findFragmentByTag(<tag of target fragment>).
For the more information check the link Communication between Fragments in ViewPager.
Have you tried implementing OnPageChanged`? You can capture when the user start swiping.
do pager.setOnPageChanged(new ....) and Eclipse will show you the methods you can override.
Then you can override onPageScrollStateChanged(int state)
onPageScrollStateChanged(int state){
if (state==OnPageChangeListener.SCROLL_STATE_DRAGGING){
// update here
}
}

Categories

Resources