necesita ayuda para corregir el código para obtener la vista actual en viewpager

Need help to fix a code I saw in a https://stackoverflow.com/a/9275732/1938357. The solution I need is get the current view onany page in my viewpager based application

Below is the code for reference

public View getCurrentView(ViewPager pager) {
for (int i = 0; i < pager.getChildCount(); i++) {
    View child = pager.getChildAt(i);
    if (child.getX() <= pager.getScrollX() + pager.getWidth()
         && child.getX() + child.getWidth() >= pager.getScrollX() + pager.getWidth()) {
        return child;
     }

 }
return getChildAt(0);

I am trying to access the current view in the view pager and used the code above. It works fine when I scroll forwards. But when I scroll backwards then after 2 backward scrolls this stops working.

Public class myActivity extends FragmentActivity
//Variable declarations
protected void onCreate(Bundle savedInstanceState) {
ViewPager mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);
View CurrView;

OnPageChangeListener pageChangelistener = new OnPageChangeListener() {
  @Override
  public void onPageSelected(int pageSelected) {
    doTextViewChnges();//access the text view and update it based on pageSelected
    ---THIS IS WHERE I AM STUCK IN TRYING TO GET THE TEXTVIEW IN MY CURRENT FRAGMWNT/VIEW-------
 }

mPager.setOnPageChangeListener(pageChangelistener);
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter { 
  public ScreenSlidePagerAdapter(android.support.v4.app.FragmentManager  fm) {
    super(fm);
 }

 @Override
 public android.support.v4.app.Fragment getItem(int position) { 
    return ScreenSlidePageFragment.create(position, <other parameters I want to pass>);
 }

 @Override
 public int getCount() {
    return NUM_PAGES;
 }
}  

And below is my ScreenSlidePageFragment class

public class ScreenSlidePageFragment extends android.support.v4.app.Fragment {

public static final String ARG_PAGE = "pagenumber";
public static final String ARG_PAGEARRAY = "pages";

private int mPageNumber;
//Declare other variables

@SuppressLint("NewApi")
public static ScreenSlidePageFragment create(int pageNumber, String[] pages, int bookmarkPageNumber, String storyName, int linesInOnePage) {
    ScreenSlidePageFragment fragment = new ScreenSlidePageFragment();
    Bundle args = new Bundle();
    args.putInt(ARG_PAGE, pageNumber);
    args.putStringArray(ARG_PAGEARRAY, pages);
    fragment.setArguments(args); 
    return fragment;
}

@SuppressLint("NewApi")
public ScreenSlidePageFragment() {
}

@SuppressLint("NewApi")
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mPageNumber = getArguments().getInt(ARG_PAGE);
    pages = getArguments().getStringArray(ARG_PAGEARRAY);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    rootView = (ViewGroup) inflater
            .inflate(R.layout.activity_story, container, false);

    //load layout with all components filled up for that page
    loadView(rootView);
    return rootView;
}
public int getPageNumber() {
    return mPageNumber;
}

preguntado el 05 de mayo de 13 a las 10:05

Try to use another answer from your link: stackoverflow.com/a/8638772/1001401. It is need from you overriding only one method of PagerAdapter and add method like getCurrentView(). -

I tried that option. But it gave me classcast exception as I am using FragmentStatePagerAdapter. -

than you can try this in setPrimaryItem(): mCurrentView = ((Fragment) object).getView(); Or, if you keep your created fragments in collection use your getItem() method of adapter for taking fragment by position and getView() from it. -

classcast exception again. Below is the code private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter { public ScreenSlidePagerAdapter(android.support.v4.app.FragmentManager fm) { super(fm);} Override public android.support.v4.app.Fragment getItem(int position) {return ScreenSlidePageFragment.create(position);} Override public int getCount() { return NUM_PAGES; } Override public void setPrimaryItem(ViewGroup container, int position, Object object) { currView = ((Fragment) object).getView();} -

1 Respuestas

It is very hard to discuss in comments with example of code.

As I see in grepcode FragmentStatePagerAdapter.setPrimaryItem(), recepción object as android.support.v4.app.Fragment. But you are receive ClassCastException when trying to cast object as Fragment. Can you check your casting: do you really cast object in android.support.v4.app.Fragment no en android.app.Fragment? If all right, add your exception message to your question, please.

ACTUALIZACIÓN:

Si ScreenSlidePagerAdapter has method getCurrentView(), then your method 'getCurrentView()' can work like this:

public View getCurrentView(ViewPager pager) {
    return ((ScreenSlidePagerAdapter) pager.getAdapter()).getCurrentView();
}

Y método getCurrentView() de tu ScreenSlidePagerAdapter:

public View getCurrentView() {
    return currView;
}

ACTUALIZACIÓN 2:

I've made some modification with your code:

Your Activity with private Adapter:

public class myActivity extends FragmentActivity implements ISelectItemListener {
    // Your variable declarations and methods

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        final ViewPager pager = (ViewPager) findViewById(R.id.pager);

        mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
        pager.setAdapter(mPagerAdapter);

        pager.setOnPageChangeListener(
                new OnPageChangeListener() {
                    @Override
                    public void onPageSelected(int pageSelected) {
                        final ScreenSlidePageFragment fragment = mPagerAdapter.getFragment(pageSelected);

                        if (fragment != null) {
                            fragment.doTextViewChnges();
                        }
                    }

                    @Override
                    public void onPageScrollStateChanged(int arg0) {
                        // TODO Auto-generated method stub
                    }

                    @Override
                    public void onPageScrolled(int arg0, float arg1, int arg2) {
                        // TODO Auto-generated method stub
                    }
                });
    }

    private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
        //Your variable declarations

        private final ScreenSlidePageFragment[] mFragments;

        public ScreenSlidePagerAdapter(android.support.v4.app.FragmentManager fm) {
            super(fm);

            mFragments = new ScreenSlidePageFragment[NUM_PAGES];
        }

        @Override
        public int getCount() {
            return NUM_PAGES;
        }




        // It will create new ScreenSlidePageFragment by position if it's not exsist
        @Override
        public android.support.v4.app.Fragment getItem(int position) {
            if (getFragment(position) == null) {
                mFragments[position] = ScreenSlidePageFragment.create(position, <other parameters I want to pass>);
            }

            return getFragment(position);
        }

        // It will give you ScreenSlidePageFragment if it's exists, or null
        public ScreenSlidePageFragment getFragment(int position) {
            return mFragments[position];
        }
    }
}

Tu Fragmento:

public class ScreenSlidePageFragment extends Fragment {
    //Your variables and methods

    public static ScreenSlidePageFragment create(int pageNumber, String[] pages, int bookmarkPageNumber, String storyName, int linesInOnePage) {
        final Bundle args = new Bundle();
        args.putInt(ARG_PAGE, pageNumber);
        args.putStringArray(ARG_PAGEARRAY, pages);

        final ScreenSlidePageFragment fragment = new ScreenSlidePageFragment();
        fragment.setArguments(args); 

        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPageNumber = getArguments().getInt(ARG_PAGE);
        pages = getArguments().getStringArray(ARG_PAGEARRAY);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = (ViewGroup) inflater.inflate(R.layout.activity_story, container, false);

        loadView(rootView);
        return rootView;
    }

    public int getPageNumber() {
        return mPageNumber;
    }

    // Let's keep logic of modifications in fragment
    public void doTextViewChnges() {
        final View view = getView();
        // do what you want with your View and his children
    }
}

contestado el 06 de mayo de 13 a las 11:05

You noted a good point. I shoulld have used android.support.v4.app.Fragment. I updated the code to below and the classcastexception is gone. @Override public void setPrimaryItem(ViewGroup container, int position, Object object) { currView = ((android.support.v4.app.Fragment) object).getView(); } But can you suggest what shall I do in public void onPageSelected(int pageSelected) call in my OnPageChangeListener(which I have added to my Viewpager) to get reference to current view. - user1938357

@user1938357 , I' update my answer, but I'm not correctly understand your last question "But can you suggest what shall I do in onPageSelected() call in my OnPageChangeListener (which I have added to my Viewpager) to get reference to current view". If it not solve your problem, can ask question another way (I don't know your full code what fields and public variablies do you have, therefore I can't give you advice). - nfirex

I have updated my post with code. Also meanwhile let me try the suggestion you have made - user1938357

@user1938357 , I'm update my answer with similar modifications of your code. - nfirex

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.