NestedScrollView의 ViewPager


111

접히는 헤더 (수직 스크롤) 위에 일종의 ViewPager (수평 스크롤) 인 Google 뉴스 스탠드와 같은 인터페이스를 만들어야합니다. 내 요구 사항 중 하나는 Google IO 2015에 제시된 새로운 디자인 지원 라이브러리를 사용하는 것입니다. ( http://android-developers.blogspot.ca/2015/05/android-design-support-library.html )

Chris Banes ( https://github.com/chrisbanes/cheesesquare )가 만든 샘플을 기반으로 축소 동작을 수행 할 수 있지만 기본 LinearLayout (가로 스크롤 없음)을 사용하는 지점에 도달했습니다.

LinearLayout을 ViewPager로 바꾸려고했는데 빈 화면이 생겼습니다. 나는 너비, 무게 및 모든 종류의 뷰 그룹을 가지고 놀았지만 .. 여전히 빈 화면입니다. ViewPager와 NestedScrollView가 서로를 좋아하지 않는 것 같습니다.

HorizontalScrollView를 사용하여 해결 방법을 시도했습니다. 작동하지만 PagerTitleStrip 기능의 이점과 단일 패널에 대한 초점을 잃어 버렸습니다 (두 패널 사이에서 가로로 중지 할 수 있음).

이제 더 이상 아이디어가 없습니다. 누군가 나를 해결책으로 이끌 수 있다면 ...

감사

다음은 내 최신 레이아웃 파일입니다.

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="@dimen/header_height"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.design.widget.CollapsingToolbarLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:contentScrim="?attr/colorPrimary"
            app:expandedTitleMarginEnd="64dp"
            app:expandedTitleMarginStart="48dp"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <include
                layout="@layout/part_header"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:layout_collapseMode="parallax"/>

            <android.support.v7.widget.Toolbar
                android:id="@+id/activity_main_toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

        </android.support.design.widget.CollapsingToolbarLayout>
    </android.support.design.widget.AppBarLayout>

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

        <android.support.v4.view.ViewPager
            android:id="@+id/activity_main_viewpager"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="#FFA0"/>


    </android.support.v4.widget.NestedScrollView>
</android.support.design.widget.CoordinatorLayout>

당신은 당신의 ViewPager내부를 포장 해 보셨습니까 LinearLayout? 그것이 ViewPager제대로 렌더링되는지 궁금합니다 .
— CzarMatt

예, 시도했지만 여전히 동일한 결과입니다. 많은 구성 요소로 많은 테스트를 수행했지만 계층 구조에 관계없이 ViewPager는 NestedScrollView에서 렌더링되지 않습니다
— Kyso84

나는 ViewPager내부가 NestedScrollView유일한 레이아웃으로 테스트 앱을 만들었습니다 . 잘 작동하는 것 같습니다. 나는 또한 DrawerLayout성공적으로 떨어질 수 있었다 . 원하는 기능을 방해하는 코드의 또 다른 측면이있을 수 있습니다. 소스를 더 많이 공유하고 싶으신가요?
— CzarMatt

와우, 왼쪽 / 오른쪽 및 위 / 아래로 스 와이프 할 수 있습니까? 저는 단순히 FragmentPagerAdapter를 사용하여 호출기에 조각을 표시합니다. 대신 샘플 코드를 공유 할 수 있습니까?
— Kyso84

여기에 간단한 예제 레이아웃을 붙여 넣었습니다. pastebin.com/jXPw6mtf 편집 : ViewPager. 보기를 위아래로 스크롤하고 ViewPager왼쪽 / 오른쪽 으로 스크롤 할 수 있습니다.
— CzarMatt

답변:


128

나는이 문제를 만난다. setFillViewport (true)

<android.support.v4.widget.NestedScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:id="@+id/nest_scrollview"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="mio.kon.yyb.nestedscrollviewbug.ScrollingActivity"
tools:showIn="@layout/activity_scrolling">


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

활동 중

  NestedScrollView scrollView = (NestedScrollView) findViewById (R.id.nest_scrollview);
    scrollView.setFillViewport (true);

여기에 이미지 설명 입력


31
이것은 XML에서도 설정할 수 있습니다 . 객체에 추가 android:fillViewport="true"하기 만하면 NestedScrollView됩니다. 문서 로이 속성을 설명합니다 Defines whether the scrollview should stretch its content to fill the viewport..
— Krøllebølle 2015

7
이것은 자리 표시 자 조각의 스크롤 문제를 해결하지 못합니다
— Atieh

3
감사! 내가 앉아있는 android:fillViewport="true"에 NestedScrollView와 내부 fragment내가 가지고 listView내가 앉은 곳 android:nestedScrollingEnabled="true".. 스크롤 문제 수정
— radubogdan

@ Krøllebølle NestedScrollView에는이 속성이 없으므로 프로그래밍 방식으로 설정해야합니다.

예, 이것은 나를 위해 작동합니다. Viewpager의 높이를 NestedScrollView 내에서 match_parent로 설정하면 뷰가 표시되지 않는 문제가 있습니다.
— Waheed Nazir 2019 년

71

좋아요, 저는 ViewPager및 NestedScrollView. 내가 직면 한 문제는 높이 ViewPager와 ListView. 그래서 나는에 약간 수정했다 ListView및 ViewPager's높이 측정합니다.

누군가 코드를 살펴보고 싶다면 여기 링크가 있습니다 : https://github.com/TheLittleNaruto/SupportDesignExample/

산출:

여기에 이미지 설명 입력


조각에 목록보기가 없으면 작동하지 않습니다. 모든 조각에 대해 항목 수가 동일하면 목록보기도 작동합니다.
— Pankaj Arora

3
나는 할 수있다 조금 파티에 늦었지만, 나는이 오늘 일하고, 나는 추가 응용 프로그램과 함께 작업 (주로)를 가지고 : layout_behavior = "@ 문자열 / appbar_scrolling_view_behavior"는 ViewPager 모두 와 의 상위 뷰 각 조각.
— Graeme

1
이것이 효과가 있다는 것은 의심의 여지가 없지만 이것이 문제를 지나치게 복잡하게하지 않습니까? 나는 제거 NestedScrollView하고 LinearLayout대신 사용하여 이것을 해결했습니다 . 전체 목적이 ViewPager 내에서 내용을 스크롤 NestedScrollView하는 LinearLayout것이라면 오버 A를 사용 하면 어떤 이점이 있습니까? 내가 틀렸다면 나를 고쳐주세요. : x 감사합니다
— Cramps

1
정말 고맙습니다! 나는 내 머리카락을 꺼내는 시점에 있었고 WrapContentHeightViewPager는 매력처럼 작동합니다. 내가 당신 께 신세를지는 거죠!
— Mavamaarten

1
완벽한 솔루션. 감사. 그것은 나를 위해
— Mrunal

42

추가 android:fillViewport="true"귀하에 NestedScrollView. 기간.


2
그것은 문제를 해결하지만 뷰 페이지 높이는 일치하는 부모가 될 것입니다 (전체 페이지 높이를 취합니다).
— Manukumar

27

NestedScrollView 내부에 ViewPager를 배치하는 대신 다른 방법으로 수행하십시오.

본질적으로 Fragment의 레이아웃 인 ViewPager 내의 자식 뷰에 NestedScrollView를 배치합니다. 또한 Fragment의 목록 레이아웃이 매우 간단한 경우 NestedScrollView를 사용할 필요가 없을 가능성이 매우 높습니다.

예제 레이아웃

활동의 레이아웃 :

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/app_bar"
        android:layout_width="match_parent"
        android:layout_height="@dimen/app_bar_height"
        android:fitsSystemWindows="true"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/toolbar_layout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            app:contentScrim="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|exitUntilCollapsed|snap">

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:minHeight="@dimen/app_bar_height"
                android:scaleType="centerCrop"
                android:src="@drawable/my_bg"
                app:layout_collapseMode="parallax"
                app:layout_collapseParallaxMultiplier="0.8"
                app:layout_scrollFlags="scroll|enterAlways|enterAlwaysCollapsed" />

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin"
                app:popupTheme="@style/AppTheme.PopupOverlay" />

        </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <android.support.design.widget.TabLayout
            android:id="@+id/content_tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

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

</android.support.design.widget.CoordinatorLayout>

TabLayout이 필요하지 않은 경우 LinearLayout을 버리고 ViewPager를 독립형으로 만들 수 있습니다. 그러나 app:layout_behavior="@string/appbar_scrolling_view_behavior"ViewPager 속성에서 사용해야 합니다.

간단한 조각의 레이아웃 :

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/recycler_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

복잡한 조각의 레이아웃 :

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:fillViewport="true"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <android.support.v7.widget.RecyclerView
            android:id="@+id/recycler_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Hello World"/>
    </RelativeLayout>
</android.support.v4.widget.NestedScrollView>

예제 앱 : CollapsingToolbarPoc

여기에 이미지 설명 입력


이것은 나를 위해 그것을 한 것입니다. 감사!
— rjr-apps 2019

Ino, 이것은 작동하는 것 같지만 TabLayout 위에 뷰를 하나 더 추가하면 깨집니다. 도움을 주시겠습니까?
— hushed_voice

당신은 내 날을 구했습니다. :)
— androidXP

20

같은 문제가있었습니다.

ViewPager 주위 에 NestedScrollView를 배치하면 작동하지 않습니다.

그래도 작동하는 것은 NestedScrollView를 ViewPager 내부에서로드하는 조각의 레이아웃 안에 넣는 것 입니다.

<android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">
        <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@id/fragment_detail"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="fill_vertical"
            android:orientation="vertical">
    ...Content...
    </LinearLayout>
</android.support.v4.widget.NestedScrollView>


콘텐츠가 다른 NestedScrollView가있는 코디네이터 레이아웃이면 작동합니까? 그리고 부모 CoordinatorLayout은 거기에서 스크롤 이벤트를 수신합니까?
— Atieh

이것은 나를 위해 일합니다. ViewPager 대신 내 ViewPager의 모든 항목에 NestedScrollView를 추가합니다. 감사.
— jerogaren

ur 솔루션에 따라 조각에 swipefreshlayout이 있습니다. NestedScrollview를 조각에, swipeRefreshLayout 위에 넣습니다. 그러면 데이터가로드되지 않습니다. 작동하지 않았습니다.
— Palak Darji 2016

16

이렇게 시도 할 수 있습니다. viewpager는 잘 작동하지만 viewpager의 높이는 고정되어 있습니다.

나는 여전히 더 나은 해결책을 찾고 있습니다. 그래서 어떤 점이 더 잘할 수 있는지 알려주십시오.

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

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:minHeight="800dp"
        android:orientation="vertical">

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

"android.support.design.widget.CoordinatorLayout"및 축소 도구 모음으로 캡슐화하려고 했습니까?
— Kyso84 2015-06-05

솔루션은 문제가 높이에 있음을 증명하는 것 같습니다. 아직 @Paul 개선 사항을 찾았습니까?
— jasxir

3
이것은 나를 위해 일했지만 nestedview에서 setFillViewport (true)를 호출해야했습니다.
— larrytech

12

나는 같은 문제가 있었고 몇 가지 변경 사항으로 수정했습니다. ViewPager내에서 작동하지 않습니다 NestedScrollView. 간단히 ViewPager귀하의 CoordinatorLayout. 그런 다음 각 ViewPager의 Fragment에 대한 콘텐츠를 NestedScrollView. 그게 다야.


콘텐츠가 다른 NestedScrollView가있는 코디네이터 레이아웃 인 경우에도?
— Atieh

1
조각 목록보기 데이터가이 방법으로로드되지 않습니다!
— Palak Darji

5

시차 효과를 얻기 위해 NestedScrollView를 사용할 필요가 없습니다. 다음과 같이 시도하십시오.

<android.support.design.widget.CoordinatorLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:animateLayoutChanges="true">

        <android.support.v7.widget.Toolbar
            android:id="@+id/my_toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layout_scrollFlags="scroll|enterAlways"/>

        <android.support.design.widget.TabLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/my_tab_layout"
            android:fillViewport="false"
            app:tabMode="fixed"/>
     </android.support.design.widget.AppBarLayout>

            <android.support.v4.view.ViewPager
                android:id="@+id/my_view_pager"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

</android.support.design.widget.CoordinatorLayout>

3
모든 ViewPager조각이 ether RecyclerView, 또는 NestedScrollView. 그들은 (예를 들어하지 않은 경우 ListView), 다음 위의 롤리팝과에 대한 해결 방법은 호출하는 것입니다listView.setNestedScrollingEnabled(true)
— AndyDeveloper

마지막으로 추가 스크롤 컨테이너를 추가하지 않고도 작동합니다! Btw 당신은 xml에서도 setNestedScrollingEnabled (true)를 설정할 수 있습니다 : android : nestedScrollingEnabled = "true"
— Analizer

1
내 앱을 실행하면 하나의 탭에서 도구 모음을 접고 탭을 전환 한 다음 도구 모음을 다시 아래로 당기면 비어 있습니다. 다시 가져 오려면 축소되지 않은 상태에서 탭을 전환해야합니다. 너무 가깝지만 지금까지 :(
— -May

4

아래에 NestedScrollView가있는 앱 도구 모음이있는 레이아웃이 있었고 중첩 된 도구 모음 내부에는 LinearLayout이 있었고 LinearLayout 아래에는 뷰 페이저가있었습니다. 아이디어는 NestedScrollView 내부의 LinearLayout이 수정되었습니다.보기 페이저의보기 사이에서 왼쪽 / 오른쪽으로 슬라이드 할 수 있지만이 콘텐츠는 수평으로 이동하지 않습니다. 적어도 . 중첩 된 스크롤보기로 인해 모든 콘텐츠를 세로로 스크롤 할 수 있어야합니다. 그게 아이디어였습니다. 그래서 중첩 된 NestedScrollView 높이를 match_parent로 설정하고 뷰포트를 채운 다음 모든 자식 레이아웃 / ViewPager를 wrap_content로 설정했습니다.

내 머릿속에서 옳았다. 그러나 작동하지 않았습니다. ViewPager를 사용하면 뷰 페이저 페이지 콘텐츠가 현재 화면의 맨 아래로 밀려 났는지 여부에 관계없이 왼쪽 / 오른쪽으로 이동할 수 있지만 수직 스크롤은 없습니다. 기본적으로 ViewPager가 다양한 페이지에서 wrap_content를 존중하지 않기 때문입니다.

ViewPager를 서브 클래 싱하여 현재 선택된 항목에 따라 높이를 변경하여 layout_height = "wrap_content"처럼 동작하도록 강제하여이 문제를 해결했습니다.

public class ContentWrappingViewPager extends ViewPager {

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

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

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

        int height = 0;
        if (getChildCount() > getCurrentItem()) {
            View child = getChildAt(getCurrentItem());
            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);
    }
}

솔루션은 이 답변 에서 영감을 받았습니다 . 나를 위해 일했습니다!


하지만 스크롤 뷰가 자동으로 맨 위로 스크롤됩니까? 이 문제를 해결하는 방법?
— Vivek Kumar

4

이 줄을 NestedScrollView에 넣으십시오.

android:fillViewport="true"

감사합니다. CollapsingToolbarLayout을 직접 터치하여 스크롤하려면 어떻게해야합니까?
— Pratik Saluja

3

주 레이아웃에서 NestedScrollView 를 제거 하고 ViewPager 에서로드해야하는 모든 Fragment 레이아웃에 부모 로 삽입 하여이 문제를 해결했습니다.


3

아래의 맞춤 수업을 사용하여 문제를 해결하세요. pagechangelistener에서 onRefresh () 메서드를 호출하는 것을 잊지 마십시오.

public class ContentWrappingViewPager extends ViewPager
{
    private int width = 0;
    public ContentWrappingViewPager(Context context) {
        super(context);
    }

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

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        int height = 0;
        width = widthMeasureSpec;
        if (getChildCount() > getCurrentItem()) {
            View child = getChildAt(getCurrentItem());
            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);
    }

    public void onRefresh()
    {
        try {
            int height = 0;
            if (getChildCount() > getCurrentItem()) {
                View child = getChildAt(getCurrentItem());
                child.measure(width, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
                int h = child.getMeasuredHeight();
                if(h > height) height = h;
            }

            int heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
            ViewGroup.LayoutParams layoutParams = this.getLayoutParams();
            layoutParams.height = heightMeasureSpec;
            this.setLayoutParams(layoutParams);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

2

비슷한 문제가 발생했습니다 (하지만 CollapsingToolbarLayout, 내에서 단순한 Toolbar+ ). 내에서 의 내용을 아래로 스크롤 할 때 툴바가 보이지 않게 스크롤하기를 원 했습니다 .TabLayoutAppBarLayoutViewPagerNestedScrollView

내 레이아웃은 다음과 같습니다.

<android.support.design.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">

        <android.support.design.widget.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:animateLayoutChanges="true">

            <android.support.v7.widget.Toolbar
                android:id="@+id/my_toolbar"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:layout_scrollFlags="scroll|enterAlways"/>

            <android.support.design.widget.TabLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/my_tab_layout"
                android:fillViewport="false"
                app:tabMode="fixed"/>
         </android.support.design.widget.AppBarLayout>

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

                <android.support.v4.view.ViewPager
                    android:id="@+id/my_view_pager"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                     app:layout_behavior="@string/appbar_scrolling_view_behavior">
                </android.support.v4.view.ViewPager>
         </android.support.v4.widget.NestedScrollView>

</android.support.design.widget.CoordinatorLayout>

이 레이아웃은 의도 한대로 작동하지 않았지만 단순히를 제거 NestedScrollView하고 LinearLayout대신 a 를 사용하여 해결했습니다 . Android 지원 라이브러리 v23.1.0에서 즉시 작동했습니다. 레이아웃이 완성 된 방법은 다음과 같습니다.

<android.support.design.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">

        <android.support.design.widget.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:animateLayoutChanges="true">

            <android.support.v7.widget.Toolbar
                android:id="@+id/my_toolbar"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:layout_scrollFlags="scroll|enterAlways"/>

            <android.support.design.widget.TabLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/my_tab_layout"
                android:fillViewport="false"
                app:tabMode="fixed"/>
         </android.support.design.widget.AppBarLayout>

         <LinearLayout
            android:orientation="vertical"
            android:id="@+id/container"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginBottom="4dp"
            app:layout_behavior="@string/appbar_scrolling_view_behavior">

                <android.support.v4.view.ViewPager
                    android:id="@+id/my_view_pager"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                     app:layout_behavior="@string/appbar_scrolling_view_behavior">
                </android.support.v4.view.ViewPager>
         </LinearLayout>

</android.support.design.widget.CoordinatorLayout>

추신 : 이것은 실제로 내 프로젝트에서 두 개의 레이아웃 파일이었습니다. 여기에 복사하여 붙여 넣은 다음 단일 파일처럼 구성하려고했습니다. 복사해서 붙여 넣다가 엉망이 됐다면 미안하지만 그럴 경우 알려 주시면 고칠 수 있습니다.


1

다음은 뷰 페이저의 적절한 높이를 보장해야합니다. 조각은 뷰 페이저에서 제공하는 첫 번째 조각입니다.

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

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">

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

        <fragment
            class="com.mydomain.MyViewPagerFragment"
            android:id="@+id/myFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:visibility="gone"/>

    </LinearLayout>

</android.support.v4.widget.NestedScrollView>

1

저도 같은 소원, 둥지 a를 가지고 ViewPager, 안쪽을 NestedScrollView. 그러나 그것은 나에게도 효과가 없습니다. 제 경우 ViewPager에는는 내부에 Fragment있으므로 서랍과의 상호 작용에 따라 콘텐츠를 전환 할 수 있습니다. 물론 AppBar, 축소 등 지원 라이브러리의 모든 새로운 기능이 작동해야합니다.

사용자가 페이저에서 페이지를 세로로 스크롤하면 다른 페이지도 동일하게 스크롤하여 페이저 자체가 스크롤 한 전체적인 인상을 사용자에게 제공합니다.

내가 한 일은 더 이상 ViewPager내부에 포함하지 않고 NestedScrollView대신 포함 된 조각의 내용을 NestedScrollView.

그런 다음 하나의 조각에 스크롤이있는 경우 컨테이너에 새 스크롤 위치를 알려주고이를 저장합니다.

마지막으로, 호출기에서 감지 된 왼쪽 또는 오른쪽으로 스 와이프하면 ( addOnPageChangeListener드래그 상태 찾기 사용 ) 대상이 스크롤해야하는 위치 (컨테이너 지식에 따라)가 내가 가져온 조각에서 정렬되도록 왼쪽 또는 오른쪽 조각에 알립니다.


그래서 본질적으로 자신의 ViewPager 구현을 작성 했습니까? 이것에 대한 코드를 공유 할 수 있습니까?
— joseph 16

이와 비슷한 작업을 수행했습니다 (올바르게 이해하는 경우). 중첩 된 스크롤 뷰 대신 tablayout (필요한 경우)과 뷰 페이저를 포함하는 코디네이터 레이아웃에서 선형 레이아웃을 수행하는 것입니다. 조각 자체에는 중첩 된 스크롤 뷰가 루트 요소로 포함됩니다. 이것은 나를 위해 작동하지만 각 조각에서 반복하는 대신 중첩 스크롤 뷰를 하나만 사용하는 것이 좋습니다.
— Chris

0

한 가지 작업 솔루션을 알고 있습니다. CoordinatorLayout과 함께 Activity를 사용하고 컨테이너 인 FrameLayout을 사용합니다. 그때. 조각 관리자를 사용하여 조각을 컨테이너에 넣습니다. 예를 들어 내 코드 :

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<android.support.design.widget.AppBarLayout
    android:id="@+id/appbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:elevation="0dp">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        app:layout_scrollFlags="scroll|enterAlways"
        android:layout_height="@dimen/toolbar_height"
        android:background="?attr/colorPrimary"
        android:gravity="center">

    </android.support.v7.widget.Toolbar>


</android.support.design.widget.AppBarLayout>

<FrameLayout
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

</FrameLayout>

그리고 조각 :

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.improvemdia.inmyroom.MainFragment">

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

그런 다음 FragmentManager를 사용하십시오.

getSupportFragmentManager().beginTransaction()
            .replace(R.id.container, new MainFragment())
            .commit();

LinearLayout여기서는 Fragment의 레이아웃이 불필요 하다고 생각합니다 . 내 대답을 참조하십시오. 내 활동의 레이아웃에서 LinearLayout대신 a 를 사용 FrameLayout했으며 내 조각의 루트는 ViewPager (래핑 레이아웃 없음)입니다.
— 경련

0

몇 시간 동안 위의 모든 제안을 시도한 후 마침내 작동했습니다. 핵심은 NestedScrollView내부 PageViewer에 넣고 두 뷰 모두layout_behavior 에 '@string/appbar_scrolling_view_behavior'대해 설정 하는 것 입니다 . 최종 레이아웃은 다음과 같습니다.

<CoordinatorLayout>
    <ViewPager app:layout_behavior="@string/appbar_scrolling_view_behavior">
        <NestedScrollView fillViewport="true" app:layout_behavior="@string/appbar_scrolling_view_behavior">
            <Content>...</Content>
        </NestedScrollView>
    </ViewPager>
    <AppBarLayout>...</AppBarLayout>
</CoordinatorLayout>

0

xml 에서 NestedScrollView 를 제거 하고이 코드를 클래스에 추가했습니다.

yourGridView.setNestedScrollingEnabled(true);


0

실제로 NestedScrollView는 CoordinatorLayout에서 CollapsingToolbarLayout의 직접적인 형제 일 필요가 없습니다. 나는 정말 기묘한 것을 성취했습니다. appbar_scrolling_view_behavior는 2 개의 중첩 조각에서 작동합니다.

내 활동 레이아웃 :

<android.support.design.widget.CoordinatorLayout>

    <android.support.design.widget.AppBarLayout>

            <android.support.design.widget.CollapsingToolbarLayout>

                <include
                    layout="@layout/toolbar"/>

            </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>

    <FrameLayout
        android:id="@+id/container"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

</android.support.design.widget.CoordinatorLayout>

"container"frameLayout에서이 조각을 부풀 렸습니다.

<android.support.constraint.ConstraintLayout>

    ... some content ...

    <android.support.v4.view.ViewPager/>

    ...

</android.support.constraint.ConstraintLayout>

그리고 그 ViewPager 내부의 조각은 다음과 같습니다.

<RelativeLayout>

    <android.support.v7.widget.RecyclerView/>

    ....

</RelativeLayout>

NestedScrollView가 CoordinatorLayout 자식 계층 구조와 스크롤 동작에서 너무 깊을 수 있다는 사실은 저를 놀라게했습니다.

당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.