0

我想设置视图页面滚动视图内,但它不显示没有指定具体的高度。设置ViewPager滚动视图内没有指定它的高度

<android.support.v4.widget.NestedScrollView 
       android:layout_width="match_parent" 
       android:layout_height="match_parent" 
       android:id="@+id/svRecord" 
       android:fillViewport="true" 
       app:layout_behavior="@string/appbar_scrolling_view_behavior"> 

        <android.support.v4.view.ViewPager 
         android:layout_width="fill_parent" 
         android:layout_height="fill_parent" 
         android:id="@+id/pager" 
        /> 
      </android.support.v4.widget.NestedScrollView> 

是否有任何为什么设置滚动视图没有指定高度?

我试图设置它的高度为0dp并指定重量1,但它仍然没有显示。

回答

1

在xml文件中声明的每个视图必须存在layout_height和layout_width。如果您通过java代码设置ViewPager的高度,那么您可以将height设置为0dp,并在呈现视图之前确保在java代码中设置其布局参数。

+0

我试图以编程方式设置,但仍然没有工作:( LinearLayout.LayoutParams PARAMS =新LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT); tabView.setLayoutParams(PARAMS); –

+0

不,你不应该使用match_parent,但实际上计算视图大小并将它们传递到layoutparams中 – Bhargav

+0

但视图大小在每个视图中都是动态的。在viewpager中设置视图大小 –

1

ViewPager现在不支持wrap_content,因为它不会同时加载所有子代,这意味着它无法获得适当的度量。因此,像这样定制它:)

public class MagicViewPager extends ViewPager { 

public MagicViewPager(Context context, AttributeSet attrs) { 
    super(context, attrs); 
} 

@Override 
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 
    // super has to be called in the beginning so the child views can be 
    // initialized. 
    super.onMeasure(widthMeasureSpec, heightMeasureSpec); 

    if (getChildCount() <= 0) 
     return; 

    // Check if the selected layout_height mode is set to wrap_content 
    // (represented by the AT_MOST constraint). 
    boolean wrapHeight = MeasureSpec.getMode(heightMeasureSpec) 
      == MeasureSpec.AT_MOST; 

    int width = getMeasuredWidth(); 

    View firstChild = getChildAt(0); 

    // Initially set the height to that of the first child - the 
    // PagerTitleStrip (since we always know that it won't be 0). 
    int height = firstChild.getMeasuredHeight(); 

    if (wrapHeight) { 

     // Keep the current measured width. 
     widthMeasureSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY); 

    } 

    int fragmentHeight = 0; 
    fragmentHeight = measureFragment(((Fragment) getAdapter().instantiateItem(this, getCurrentItem())).getView()); 

    // Just add the height of the fragment: 
    heightMeasureSpec = MeasureSpec.makeMeasureSpec(height + fragmentHeight, 
      MeasureSpec.EXACTLY); 

    // super has to be called again so the new specs are treated as 
    // exact measurements. 
    super.onMeasure(widthMeasureSpec, heightMeasureSpec); 
} 

public int measureFragment(View view) { 
    if (view == null) 
     return 0; 

    view.measure(0, 0); 
    return view.getMeasuredHeight(); 
}} 
+0

顺便说一句,我写WCViewPager类,很好地处理wrap_content(也在案件儿童的尺寸不一样): https://github.com/rnevet/WCViewPager – Raanan

1

原因是ScrollView需要知道它的所有子视图的确切高度,才能呈现它。 viewpager的高度在加载页面之前是不知道的。

相关问题