Can anyone help me to find out what can be the issue with this program.
In the onCreate()
method the findViewById()
returns null for all ids and th
add those views to the pager adapter before accessing them.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adapter = new MyPagerAdapter();
pager = (ViewPager) findViewById(R.id.main_pager);
pager.setAdapter(adapter);
layout1 = (LinearLayout) findViewById(R.id.first_View);
layout2 = (LinearLayout) findViewById(R.id.second_View);
layout3 = (LinearLayout) findViewById(R.id.third_View);
}
in the pager adapter:
public Object instantiateItem(View collection, int position) {
if(position == 0){
View layout = inflater.inflate(R.layout.activity_first, null);
((ViewPager) collection).addView(layout);
return layout;
}
... and so forth.
}
from here you can access them via findViewById.
The findViewById
method must find what is in the layout (which you called in the setContentView
)
The views you're trying to get are not defined in your activity_main
layout. You need to programmatically inflate the views you're trying to add to the pager.-
@Override
public Object instantiateItem(ViewGroup collection, int position) {
LinearLayout l = null;
if (position == 0) {
l = (LinearLayout) View.inflate(this, R.layout.activity_first, null);
}
if (position == 1) {
l = (LinearLayout) View.inflate(this, R.layout.activity_second, null);
}
if (position == 2) {
l = (LinearLayout) View.inflate(this, R.layout.activity_third, null);
}
collection.addView(l, position);
return l;
}
In Android, findViewById(R.id.some_id)
works when you are finding view in the layout set.
That is, if you have set a layout say:
setContentView(R.layout.my_layout);
Views can be found only in this layout (my_layout).
In your code layout1
, layout2
, layout3
all are three different layouts and they are not set to the activity.