Как прокрутить вертикально Viewpager - PullRequest
4 голосов
/ 06 апреля 2019

Я не могу прокрутить пейджер по вертикали. когда я использую NestedScrollView в дочернем макете, страницы становятся пустыми. Я пробовал много решений. Но не удалось.

Это мой основной фрагмент nav_swipe.xml

<?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:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

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


        <android.support.v4.view.PagerTitleStrip
            android:id="@+id/pager_title_strip"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="top"
            android:background="#33b5e5"
            android:paddingBottom="4dp"
            android:paddingTop="4dp"
            android:textColor="#fff" />

    </android.support.v4.view.ViewPager>
</android.support.design.widget.CoordinatorLayout>

Это дочерний макет фрагмента: фрагмент_а.xml. где я использовал nestedscrollview, но не нашел решения.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    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:id="@+id/constraintLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/text1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:textColor="@color/colorPrimaryDark"
        android:layout_marginBottom="@dimen/activity_vertical_margin"
        android:layout_marginRight="@dimen/activity_horizontal_margin"
        android:layout_marginLeft="@dimen/activity_horizontal_margin"
        android:layout_marginTop="@dimen/activity_vertical_margin"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="@+id/constraintLayout"
        tools:layout_constraintLeft_creator="1"
        tools:layout_constraintTop_creator="1" />

</android.support.constraint.ConstraintLayout>

Это SwipeNav.java

public class SwipeNav extends Fragment {

private MyPagerAdapter myPagerAdapter;
private ViewPager viewPager;


@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.nav_swipe, container, false);
        myPagerAdapter = new MyPagerAdapter(getChildFragmentManager(),getContext());
        viewPager = (ViewPager) rootView.findViewById(R.id.pager);
        viewPager.setAdapter(myPagerAdapter);
        return rootView;
    }


@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

}

Это MyPagerAdapter.java

public class MyPagerAdapter extends FragmentStatePagerAdapter {
    private Context context;
    private String[] tabTitlesArray = null;
    public MyPagerAdapter(FragmentManager fm, Context context) {
        super(fm);
        tabTitlesArray = context.getResources().getStringArray(R.array.tab_titles);
        this.context= context;
    }

    @Override
    public Fragment getItem(int i) {
        Fragment fragment = new AFragment();
        Bundle args = new Bundle();
        args.putString(AFragment.ARG_OBJECT, tabTitlesArray[i]);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public int getCount() {
        return tabTitlesArray.length;
    }

    @Override
    public CharSequence getPageTitle(int position) {

        //return tabTitleArray[position];
        return "OBJECT " + (position + 1);
    }
}

Это AFragment.java

public class AFragment extends Fragment {
    public static final String ARG_OBJECT = "object";
    public AFragment() {
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_a, container, false);
        Bundle args = getArguments();
        ((TextView) rootView.findViewById(R.id.text1)).setText(args.getString(ARG_OBJECT));
        return rootView;
    }
    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }
}

Ответы [ 2 ]

3 голосов
/ 09 апреля 2019

любезно используйте ViewPager.PageTransformer, чтобы создать иллюзию вертикального ViewPager.Для достижения прокрутки по вертикали вместо горизонтали.

/**
 * Uses a combination of a PageTransformer and swapping X & Y coordinates
 * of touch events to create the illusion of a vertically scrolling ViewPager. 
 * 
 * Requires API 11+
 * 
 */
public class VerticalViewPager extends ViewPager {

public VerticalViewPager(Context context) {
    super(context);
    initiate();
}

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

private void initiate() {
    // The majority of the magic happens here
    setPageTransformer(true, new VerticalPageTransformer());
    // The easiest way to get rid of the overscroll drawing that happens on the left and right
    setOverScrollMode(OVER_SCROLL_NEVER);
}

private class VerticalPageTransformer implements ViewPager.PageTransformer {

    @Override
    public void transformPage(View view, float position) {

        if (position < -1) { // [-Infinity,-1)
            // This page is way off-screen to the left.
            view.setAlpha(0);

        } else if (position <= 1) { // [-1,1]
            view.setAlpha(1);

            // Counteract the default slide transition
            view.setTranslationX(view.getWidth() * -position);

            //set Y position to swipe in from top
            float yPosition = position * view.getHeight();
            view.setTranslationY(yPosition);

        } else { // (1,+Infinity]
            // This page is way off-screen to the right.
            view.setAlpha(0);
        }
    }
}

/**
 * Swaps the X and Y coordinates of your touch event.
 */
private MotionEvent swapXY(MotionEvent ev) {
    float width = getWidth();
    float height = getHeight();

    float newX = (ev.getY() / height) * width;
    float newY = (ev.getX() / width) * height;

    ev.setLocation(newX, newY);

    return ev;
}

@Override
public boolean onInterceptTouchEvent(MotionEvent ev){
    boolean intercepted = super.onInterceptTouchEvent(swapXY(ev));
    swapXY(ev); // return touch coordinates to original reference frame for any child views
    return intercepted;
}

@Override
public boolean onTouchEvent(MotionEvent ev) {
    return super.onTouchEvent(swapXY(ev));
}

}
2 голосов
/ 06 апреля 2019

Попробуйте этот код:

РЕДАКТИРОВАТЬ ПЛАН

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">


<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">



    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"/>

    </LinearLayout>

</ScrollView>

РЕДАКТИРОВАТЬ: Для основного попробовать этот код

<RelativeLayout 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/main_layout"
android:layout_height="match_parent"
tools:context=".com.example.thomas.activity.MainActivity">






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



    <android.support.design.widget.TabLayout
        android:id="@+id/main_tabs"
        android:layout_width="match_parent"
        app:tabIndicatorColor="@android:color/white"
        app:tabSelectedTextColor="@android:color/white"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
    </android.support.design.widget.TabLayout>

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

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

Если не работает, пожалуйста, покажите немного кода Java

РЕДАКТИРОВАТЬ

Я обновил макет для фрагмента

Теперь вот код для адаптера фрагмента:

public class FragmentAdaptater extends FragmentPagerAdapter

{

private final List<Fragment>  lstFragment = new ArrayList<>();
private final List<String> lstTitles = new ArrayList<>();

public FragmentAdaptater(FragmentManager fm) {
    super(fm);
}


@Override
public Fragment getItem(int i) {
    return lstFragment.get(i);
}

@Nullable
@Override
public CharSequence getPageTitle(int position) {
    return lstTitles.get(position);
}

@Override
public int getCount() {
    return  lstTitles.size();
}


public void AddFragment (Fragment fragment , String title)
{
    lstFragment.add(fragment);
    lstTitles.add(title);
}

}

И код в основном:

public class MainActivity extends AppCompatActivity {


private Toolbar mToolbar;
private FragmentPagerAdapter fragmentadaptater2;
private ViewPager mviewpager;     
private TabLayout mtablayout;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);


    setContentView(R.layout.activity_main_2);
    mviewpager = (ViewPager) findViewById(R.id.main_tabs_pager);
    mToolbar = (Toolbar) findViewById(R.id.main_page_toolbar);
    mtablayout = (TabLayout) findViewById(R.id.main_tabs);

    setSupportActionBar(mToolbar);




    fragmentadaptater2 = new FragmentAdaptater(getSupportFragmentManager());


    ((FragmentAdaptater) fragmentadaptater2).AddFragment(new YOURFRAGMENT(),"YOUR FRAGMENT NAME");
    ((FragmentAdaptater) fragmentadaptater2).AddFragment(new YOURFRAGMENT(),"YOUR FRAGMENT NAME");

        ((FragmentAdaptater) fragmentadaptater2).AddFragment(new YOURFRAGMENT(),"YOUR FRAGMENT NAME");




    mviewpager.setAdapter(fragmentadaptater2);
    mtablayout = (TabLayout) findViewById(R.id.main_tabs);
    mtablayout.setupWithViewPager(mviewpager);

}

...