[Android] ViewPager 내부 내용 높이에 따른 스크롤 설정하기
2021. 4. 14. 16:25ㆍ모바일/Android_Java
ViewPager 내부 내용 높이에 따른 스크롤 설정하기
PagerApdater
@Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
super.setPrimaryItem(container, position, object);
if (position != mCurrentPosition && container instanceof DynamicHeightViewPager) {
Fragment fragment = (Fragment) object;
DynamicHeightViewPager pager = (DynamicHeightViewPager) container;
if (fragment != null && fragment.getView() != null) {
mCurrentPosition = position;
pager.measureCurrentView(fragment.getView());
}
}
}
DynamicHeightViewPager
public class DynamicHeightViewPager extends ViewPager {
View mCurrentView;
public DynamicHeightViewPager(@NonNull Context context) {
super(context);
}
public DynamicHeightViewPager(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
// @Override
// protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// super.onMeasure(widthMeasureSpec, heightMeasureSpec);
//
// int height = 0;
// int childWidthSpec = MeasureSpec.makeMeasureSpec(
// Math.max(0, MeasureSpec.getSize(widthMeasureSpec) -
// getPaddingLeft() - getPaddingRight()),
// MeasureSpec.getMode(widthMeasureSpec)
// );
// for (int i = 0; i < getChildCount(); i++) {
// View child = getChildAt(i);
// child.measure(childWidthSpec, MeasureSpec.UNSPECIFIED);
// int h = child.getMeasuredHeight();
// if (h > height) height = h;
// }
//
// if (height != 0) {
// heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
// }
//
// super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// }
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (mCurrentView != null) {
mCurrentView.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
int height = Math.max(0, mCurrentView.getMeasuredHeight());
heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
public void measureCurrentView(View currentView) {
mCurrentView = currentView;
requestLayout();
}
}
Activity의 xml
<ScrollView
android:id="@+id/sv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<kr.co.koreastock.mts.android.custom.DynamicHeightViewPager
android:id="@+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</ScrollView>
'모바일 > Android_Java' 카테고리의 다른 글
[Android] Webview 뒤로가기 (0) | 2021.05.07 |
---|---|
[Android] android weburl get paramater (0) | 2021.04.22 |
[Android] pdf open with instantly(immediatly) close error + Failed to find configured root that contains /data~ (0) | 2021.04.14 |
[Android] 스크롤 하면서 라디오버튼 체크 변경, 체크 클릭시 하면 해당 스크롤로 가기 (0) | 2021.04.13 |
[Android] ViewPager 화면에 보일 때 호출 (setUserVisibleHint함수, mIsVisibleToUser변수) (0) | 2021.04.01 |