I'm building an android application with the following layout.
It's already known that layout_height="wrap_content"
doesn't work for the ViewPager.
My question is how to change it dynamically. The content of the ViewPager is inflated from two xml layouts, vp_statistics.xml and vp_campaigns.xml.
here's the xml for the ViewPager
<LinearLayout
android:id="@+id/topcontent_wrapper"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:orientation="vertical" >
</LinearLayout>
<LinearLayout
android:id="@+id/viewpager_wrapper"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:orientation="vertical" >
<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
Here's the code for my PagerAdapter
class MyPagerAdapter extends PagerAdapter{
@Override
public int getCount() {
// TODO Auto-generated method stub
return 2;
}
public Object instantiateItem(View collection, int pos){
LayoutInflater inflater = (LayoutInflater)collection.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
int resId = 0;
switch(pos){
case 0:
resId = R.layout.vp_statistics;
break;
case 1:
resId = R.layout.vp_campaigns;
break;
}
View view = inflater.inflate(resId, null);
((ViewPager)collection).addView(view, 0);
return view;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
// TODO Auto-generated method stub
((ViewPager)container).removeView((View)object);
}
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
// TODO Auto-generated method stub
return arg0 == ((View)arg1);
}
@Override
public Parcelable saveState() {
// TODO Auto-generated method stub
return null;
}
}
and inside my onCreate() mthod of the Activity class:
MyPagerAdapter adapter = new MyPagerAdapter();
ViewPager viewPager = (ViewPager)findViewById(R.id.viewpager);
viewPager.setAdapter(adapter);
viewPager.setCurrentItem(0);
Is there a way to get the height of the vp_statistics.xml
and vp_campaigns.xml
layouts and assign it dynamically to ViewPager (@id/viewpager)
every time the instantiateItem()
object gets called?
weightSum=2
attribute to the parent LinearLayout
, and set orientation=vertical
.layout_weight=1
. Also, set layout_height=0dip
LinearLayout
with layout_weight=1
and layout_height=0dip
I answered a similar question here.
The solution extends ViewPager to override onMeasure()
to make wrap_content
just work for the height.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With