之前我遇到了一个问题,即在ScrollView
中显示来自ViewPager
的Fragment
时遇到了问题。这是因为我们需要为ViewPager
设置准确的高度。我们不能依赖于WRAP_CONTENT
或MATCH_PARENT
。我从这里解决了这个问题。现在,我的问题是如果一个Fragment
的高度不是全屏幕,我就无法使用屏幕上空白部分滑动ViewPager
。我只能使用Fragment
可见部分进行滑动。以下是代码。
public class CustomPager extends ViewPager {
private View mCurrentView;
public CustomPager(Context context) {
super(context);
}
public CustomPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (mCurrentView == null) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
return;
}
int height = 0;
mCurrentView.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
int h = mCurrentView.getMeasuredHeight();
if (h > height) height = h;
//TODO: if (height < empty space height of a screen) height = empty space height of a screen
heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
public void measureCurrentView(View currentView) {
mCurrentView = currentView;
requestLayout();
}
public int measureFragment(View view) {
if (view == null)
return 0;
view.measure(0, 0);
return view.getMeasuredHeight();
}
}
layout.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/scroll_view"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/text2"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/text3"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<com.example.CustomPager
android:id="@+id/custom_pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</ScrollView>
ScrollView
来滚动ViewPager
的内容,请不要这样做,将ScrollView
移动到各个片段的布局中。如果您只是因为其他原因而在ViewPager
外部拥有一个ScrollView
,请在ScrollView
上设置 fillViewport 属性为 true。 - Gergely Kőrössyandroid:fillViewport=true
,但没有生效。 - Sam