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之間進行滑動切換。