ViewPager是Android中用于實(shí)現(xiàn)頁面滑動(dòng)效果的一個(gè)組件,它通常與Fragment一起使用,可以讓用戶在不同的頁面之間進(jìn)行滑動(dòng)切換。要實(shí)現(xiàn)ViewPager的頁面滑動(dòng)效果,你需要遵循以下步驟:
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);
}
}
現(xiàn)在,你已經(jīng)成功實(shí)現(xiàn)了ViewPager的頁面滑動(dòng)效果。用戶可以在Fragment1和Fragment2之間進(jìn)行滑動(dòng)切換。