I’m trying to implement ViewPager to combine two view within one activity, in which I’m facing NullPointerException when I’m trying to access items using findViewById in inflated views, my custom page adapter is as follows,
public class CustomPagerAdapter extends PagerAdapter {
@Override
public int getCount() {
return 2;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == ((View) object);
}
@Override
public void destroyItem(View view, int value, Object object) {
((ViewPager) view).removeView((View) object);
}
@Override
public Parcelable saveState() {
return null;
}
@Override
public Object instantiateItem(View collection, int position) {
LayoutInflater layoutInflater = (LayoutInflater) collection.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
int resultId = 0;
switch (position) {
case 1:
resultId = R.layout.layout2;
break;
case 0:
default:
resultId = R.layout.layout1;
break;
}
View view = layoutInflater.inflate(resultId, null);
((ViewPager) collection).addView(view, 0);
return view;
}
}
And my activity is as follows, in which I’m trying to access button which is inside layout1 which throws null value.
public class PageSwiperActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.viewpagerlayout);
Button myButton=(Button) findViewById(R.id.myButton);
}
}
My viewpagerlayout.xml contains only,
<android.support.v4.view.ViewPager
android:id="@+id/viewPagerLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
and my layout1.xml contains one button. Give me some guidance.
Thanks.
Did you set your
PageAdaptertoViewPager?If you don’t set it, then remove line with button and add this code to your activity:
instead of this
You can call
findViewByIdto get your button in this method of your adapter:after you have inflated layout which contains this button.