Fragment:
- 创建一个 Fragment:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| public class MyFragment extends Fragment { @Override public void onAttach(@NonNull Context context) { super.onAttach(context); } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view=inflater.inflate(R.layout.fragement,container,false); return view; } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); TextView textView=view.findViewById(R.id.text); textView.setText("--MyFragment2--"); } }
|
- 在 Activity 中的添加 Fragment:
Activity 的布局文件中添加存放组件:
1 2 3 4
| <FrameLayout android:id="@+id/framelayout" android:layout_width="match_parent" android:layout_height="match_parent" />
|
在 Activity 中向 FrameLayout
添加 Fragment:
1 2 3 4
| MyFragment fg= new MyFragment();
getSupportFragmentManager().beginTransaction() .add(R.id.framelayout,fg).commitAllowingStateLoss();
|
Android 还提供了隐藏和显示 Fragment 的方法,如下方法能切换 fg1 和 fg2 两 Fragment:
1 2 3 4 5 6 7 8
| if (fg1.isHidden()){ getSupportFragmentManager().beginTransaction() .hide(fg2).show(fg1).commitAllowingStateLoss(); } else { getSupportFragmentManager().beginTransaction() .hide(fg1).show(fg2).commitAllowingStateLoss(); }
|
1 2 3 4
| <androidx.viewpager.widget.ViewPager android:id="@+id/viewpager" android:layout_width="match_parent" android:layout_height="match_parent"/>
|
1 2 3 4 5 6 7 8 9 10 11 12 13
| MyFragment fg1= new MyFragment(); MyFragment fg2= new MyFragment(); MyFragment fg3= new MyFragment(); ArrayList<Fragment> fragments=new ArrayList<>(); fragments.add(fg1); fragments.add(fg2); fragments.add(fg3); ViewPager viewPager=findViewById(R.id.viewpager);
viewPager.setAdapter(new MyPagerAdapter(getSupportFragmentManager(),fragments));
viewPager.setCurrentItem(1);
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| public class MyPagerAdapter extends FragmentPagerAdapter { ArrayList<Fragment> fragments; public MyPagerAdapter(@NonNull FragmentManager fm,ArrayList<Fragment> fragments) { super(fm); this.fragments=fragments; } @NonNull @Override public Fragment getItem(int position) { return fragments.get(position); } @Override public int getCount() { return fragments.size(); } }
|
xml中:ViewPager
内嵌入 TabLayout
1 2 3 4 5
| <androidx.viewpager.widget.ViewPager ··· <com.google.android.material.tabs.TabLayout ··· /> </androidx.viewpager.widget.ViewPager>
|
FragmentPagerAdapter类中:重写 getPageTitle
方法
1 2 3 4 5
| @Nullable @Override public CharSequence getPageTitle(int position) { return titles[position]; }
|