最终效果:简单模拟微信界面
1.在activity_main中创建ViewPager布局
<androidx.viewpager2.widget.ViewPager2
android:id="@+id/viewpager"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="0dp"/>
2.创建一个BlankFragment,fragment_blank.xml的TextView 设置一个ID属性 android:id="@+id/tv"
public class BlankFragment extends Fragment {
private static final String ARG_TEXT = "param1";
private String mTextString;
private View rootView;
public BlankFragment() {
// Required empty public constructor
}
public static BlankFragment newInstance(String param1) {
BlankFragment fragment = new BlankFragment();
Bundle args = new Bundle();
args.putString(ARG_TEXT, param1);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mTextString = getArguments().getString(ARG_TEXT);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (rootView == null){
rootView = inflater.inflate(R.layout.fragment_blank, container, false);
}
initView();
return rootView;
}
private void initView() {
TextView textView = rootView.findViewById(R.id.tv);
textView.setText(mTextString);
}
}
3.创建MyFragmentPagerAdapter类
public class MyFragmentPagerAdapter extends FragmentStateAdapter {
List<Fragment> fragmentList = new ArrayList<>();
public MyFragmentPagerAdapter(@NonNull FragmentManager fragmentManager, @NonNull Lifecycle lifecycle,List<Fragment> fragments) {
super(fragmentManager, lifecycle);
fragmentList = fragments;
}
@NonNull
@Override
public Fragment createFragment(int position) {
return fragmentList.get(position);
}
@Override
public int getItemCount() {
return fragmentList.size();
}
}
4.在MainActivity中创建一个函数初始化viewpager
private void initViewPager() {
viewPager = findViewById(R.id.viewpager);
ArrayList<Fragment> fragments = new ArrayList<>();
fragments.add(BlankFragment.newInstance("主页"));
fragments.add(BlankFragment.newInstance("通讯录"));
fragments.add(BlankFragment.newInstance("发现"));
fragments.add(BlankFragment.newInstance("我"));
MyFragmentPagerAdapter pagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager(),getLifecycle(),fragments);
viewPager.setAdapter(pagerAdapter);
}
初步完成界面的左右滑动