2013-10-23 50 views

回答

0

假設執行如下所示,

<LinearLayout android:orientation="vertical"> 
    <ViewPager /> 
    <ViewPager /> 
    <ViewPager /> 
</LinearLayout> 

則ViewPagers的高度設置爲wrap_content應該具有所期望的結果。沒有必要動態地做到這一點。否則,如果你真的想/需要動態地做到這一點,只需設置ViewPager的LayoutParams從以下代碼:

LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
    LinearLayout.LayoutParams.WRAP_CONTENT, 
    LinearLayout.LayoutParams.WRAP_CONTENT); 
viewPager.setLayoutParams(lp); 

中的LayoutParams構造函數的參數是(寬,高),而且你需要更改寬度,如果你不希望它是wrap_content。

+0

我嘗試過,但沒有viewpager屏幕上顯示。他們得到的高度爲0.而且我還需要在頁面更改時動態更改它,因爲有時我在viewpager中獲得了更長的textview – neeraj

+0

您能否顯示您的佈局代碼? –

+0

與我同樣的問題。我在屏幕上沒有任何物品 –

3

問題是,「wrap_content」似乎沒有與查看傳呼機一起工作。 這裏是解決方案:

import android.content.Context; 
import android.support.v4.view.ViewPager; 
import android.util.AttributeSet; 
import android.view.View; 

public class CustomViewPager extends ViewPager { 

public CustomViewPager(Context context) { 
    super(context); 
} 

public CustomViewPager(Context context, AttributeSet attrs){ 

    super(context, attrs); 
} 

@Override 
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 

    super.onMeasure(widthMeasureSpec, heightMeasureSpec); 

    int height = 0; 
    for(int i = 0; i < getChildCount(); i++) { 

     View child = getChildAt(i); 

     child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)); 

     int h = child.getMeasuredHeight(); 

     if(h > height) height = h; 

    } 

    heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY); 

    super.onMeasure(widthMeasureSpec, heightMeasureSpec); 
} 
} 

參考: Android: I am unable to have ViewPager WRAP_CONTENT

就是這樣,不要猶豫,評論,分享你的知識和指正。