ViewPager是Android中用于实现页面滑动效果的一个组件,它通常与Fragment一起使用,可以让用户在不同的页面之间进行滑动切换。要实现ViewPager的页面滑动效果,你需要遵循以下步骤:
dependencies {
implementation 'com.android.support:support-v4:28.0.0'
}
android:id="@+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
public class Fragment1 extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment1_layout, container, false);
}
}
public class Fragment2 extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment2_layout, container, false);
}
}
public class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new Fragment1();
case 1:
default:
return new Fragment2();
}
}
@Override
public int getCount() {
return 2;
}
}
public class MainActivity extends AppCompatActivity {
private ViewPager viewPager;
private MyPagerAdapter myPagerAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = findViewById(R.id.viewPager);
myPagerAdapter = new MyPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(myPagerAdapter);
}
}
现在,你已经成功实现了ViewPager的页面滑动效果。用户可以在Fragment1和Fragment2之间进行滑动切换。