Viewpager2 and Fragments

拟墨画扇 提交于 2021-02-05 07:14:07

问题


ViewPager2 does not support direct child views

I'm trying to transition between fragments using the following code but I get the above error when using viewpager2.

Call in fragment 1 to transition to fragment 2:

getFragmentManager().beginTransaction().replace(R.id.viewPager2, new q2_fragment()).addToBackStack(null).commit();

Viewpager2 XML in Main Layout:

<androidx.viewpager2.widget.ViewPager2
            android:id="@+id/viewPager2"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="10"
            android:orientation="horizontal"
            android:scaleType="fitXY" />

Instantiation in Main:

final ViewPager2 viewPager2 = findViewById(R.id.viewPager2);
        viewPager2.setAdapter(new QuestionsActivity.ScreenSlidePagerAdapter(this));
        viewPager2.setUserInputEnabled(false);

How do I avoid this error with viewpager2?


回答1:


Would be happy to help, please elaborate on your requirement. What exactly you want to do.

If you want to go to fragment 2 from fragment 1, at a particular point then you should use interface between fragment and activity, to tell the activity to move the viewpager to the item which has fragment 2.

Interface Pattern for Fragment to Activity

Interface

public interface FragmentCallback{
    public void goTo(int pos);
}

Activity

public class MyActivity extends AppCompatActivity implements MyStringListener{

  @Override
  public void goTo(int pos){
        yourviewpagerAdapter.setCurrentItem(pos);
  }

}

public class Fragment1 {

        private FragmentCallback callBack;

        @Override
        public void onAttach(Context context) {
            super.onAttach(context);
            try {
                callBack = (FragmentCallback) context;
            } catch (ClassCastException castException) {
                /** The activity does not implement the listener. */
            }
        }

       

        public void someEvent() {
            if(callBack!=null) {
                callBack.goTo(1);
            } 
        }           

    }


来源:https://stackoverflow.com/questions/63863320/viewpager2-and-fragments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!