Reputation: 3601
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.
Upvotes: 0
Views: 2507
Reputation: 1523
Did you set your PageAdapter
to ViewPager
?
If you don't set it, then remove line with button and add this code to your activity:
final ViewPager viewPager = (ViewPager) findViewById(R.id.viewPagerLayout);
viewPager.setAdapter(new CustomPagerAdapter());
instead of this
Button myButton = (Button) findViewById(R.id.myButton);
You can call findViewById
to get your button in this method of your adapter:
@Override
public Object instantiateItem(View collection, int position) {
... // your previous code
final Button myButton = (Button) findViewById(R.id.myButton);
return view;
}
after you have inflated layout which contains this button.
Upvotes: 4
Reputation: 10349
After setContentView(R.layout.viewpagerlayout);
you are using
Button myButton=(Button) findViewById(R.id.myButton);
directly.
But actually viewpagerlayout doesn't have any view with id myButton.
So that you are getting NULL Pointer Exception. Before using findViewById, you have to add views to ViewPager layout.
In the code you posted here, it seem to be you are adding, but you have to use it after setContentView.
Upvotes: 1