not able to get the current view in Viewpager

android

Solution

You can use the setTag with the view you are returning in your instantiateItem method(PagerAdapter).

So, when you are instantiating your views in PagerAdapter the method is also `instantiateItem(ViewGroup container, int position))`, you should use setTag to your view.

Like this:

view.setTag("myview" + position);
return view;

when you need the current view:

View view = (View) pager.findViewWithTag("myview" + pager.getCurrentItem());

Problem

I am using a viewpager to display some text across multiple pages. I am trying to get the current view an I select a new page. The reason I want to get the current view is because based on the page number I am changing some properties of some view components like textview, image etc. I am using the below code for the same ``` 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) { currView = mPager.getChildAt(mPager.getCurrentItem()); myTextView = (TextView)currView.findViewById(R.id.myTextView); loadBookmarkSetting(pageSelected);//do some changes in myTextView properties based on the page number } mPager.setOnPageChangeListener(pageChangelistener); ``` Now the problem I am facing that after I scroll 3 pages and when I come to 4th page, i get nullpointer exception on the line "myTextView = (TextView)currView.findViewById(R.id.myTextView);". This is so becuase currView is null. Any ideas if I am doing something wrong here. Is there any other way to capture current view(page) in viewpager so as I can do changes on the view based on what page number I am on?

Original source

Related problems