2011-12-16 77 views
7

是否ViewPager必须是活动布局中唯一存在的对象? 我想实现这样的事情:Android ViewPager尺寸

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:id="@+id/reader_layout" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent" 
android:orientation="vertical" > 

<android.support.v4.view.ViewPager 
    android:id="@+id/page_viewer" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" /> 

<Gallery 
    android:id="@+id/miniatures_gallery" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" /></LinearLayout> 

我应该在哪里有一个大的寻呼机在上面滚动(我有)和一个较小的画廊根据该滚动。 这只显示我的寻呼机,而不是画廊。 有什么建议吗?

+1

试试这个:http://helpmeco.de/2012/1/android-viewpager-and-gallery-integration – browep 2012-02-28 23:47:52

+0

tnx这真是太好了......但是我在页面旋转时遇到了崩溃,对此有何建议? – 2012-02-29 10:15:57

+0

你有堆栈跟踪吗?你从github上获得这个项目吗,还是从教程中复制粘贴? – browep 2012-02-29 22:56:52

回答

6

ViewPager不支持wrap_content,因为它(通常)永远不会同时加载其所有子项,因此可能无法获得适当的大小(选项可能是在每次有切换页面)。

但是,您可以设置精确的尺寸(例如150dp)和match_parent
您还可以通过更改其LayoutParams中的属性height来从代码中动态修改尺寸。

0

我解决了几个黑客的问题。这涉及到:

首先,我需要一个忽略ViewPager的高度限制的布局。将其用作ViewPager项目的父级布局。

public class TallLinearLayout extends LinearLayout { 

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

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

    public TallLinearLayout(Context context, AttributeSet attrs, int defStyle) { 
     super(context, attrs, defStyle); 
    } 

    @Override 
    protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec) { 
     super.onMeasure(widthMeasureSpec, MeasureSpec.UNSPECIFIED); 
    } 
} 

我然后写的逻辑,用于调整大小ViewPager:

private class ViewPagerContentWrapper implements OnGlobalLayoutListener { 
    private ViewPager mViewPager; 

    public ViewPagerContentWrapper(ViewPager viewPager) { 
     mViewPager = viewPager; 
    } 

    @Override 
    public void onGlobalLayout() { 
     int position = mViewPager.getCurrentItem(); 
     check(position); 
     check(position + 1); 
    } 

    private void check(int position) { 
     ViewGroup vg = (ViewGroup) mViewPager.getChildAt(position); 
     View v = vg == null ? null : vg.getChildAt(0); 

     if (v != null) { 
      int height = v.getHeight(); 
      if (height > mViewPager.getHeight()) { 
       resize(height); 
      } 
     } 
    } 

    private void resize(int height) { 
     mViewPager.setLayoutParams(
       new LinearLayout.LayoutParams(
         LinearLayout.LayoutParams.MATCH_PARENT, 
         height 
       ) 
     ); 
    } 
} 

其中我注册为全局布局监听器:

viewPager.getViewTreeObserver().addOnGlobalLayoutListener(new ViewPagerContentWrapper(viewPager)); 
4

分配布局重量,以查看寻呼机作为1个&高度= 0dp而不是wrap_content

<android.support.v4.view.ViewPager 
    android:id="@+id/page_viewer" 
    android:layout_width="match_parent" 
    android:layout_height="0dp" 
    android:layout_weight="1"/>