gpt4 book ai didi

java - 选项卡 fragment 不显示

转载 作者:行者123 更新时间:2023-12-02 06:04:58 25 4
gpt4 key购买 nike

我正在尝试在 fragment 中添加选项卡(用于底部导航栏)。但是,当我运行该应用程序时,选项卡根本不显示。下面是结果的图像:

IMAGE

  • Home.java -> 应显示 2 个选项卡的 fragment ,其中包括 BlankFragment.java

  • CategoryAdapater.java -> 设置要在每个选项卡中显示的选项卡名称和 fragment

  • BlankFragment.java -> 每个选项卡上显示的空 fragment

我怎样才能让它工作?

<小时/>

Home.java(应显示选项卡的 fragment )

public class Home extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_home, container, false);

ViewPager viewPager = rootView.findViewById(R.id.viewpager);
CategoryAdapter adapter = new CategoryAdapter(getChildFragmentManager());
viewPager.setAdapter(adapter);
TabLayout tabLayout = rootView.findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);

return rootView;
}

public Home() {}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}

@Override
public void onAttach(Context context) {
super.onAttach(context);
}

@Override
public void onDetach() {
super.onDetach();
}
<小时/>

类别Adapater.java

public class CategoryAdapter extends FragmentPagerAdapter {

public CategoryAdapter(FragmentManager fm) {
super(fm);
}

@Override
public Fragment getItem(int position) {
if (position == 0) {
return new BlankFragment();
} else {
return new BlankFragment();
}
}

@Override
public int getCount() {
return 2;
}

@Override
public CharSequence getPageTitle(int position) {
if (position == 0) {
return "Devices";
} else {
return "Numbers";
}
}
}
<小时/>

BlankFragment.java

public class BlankFragment extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_blank, container, false);

return rootView;
}

public BlankFragment() {}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}

@Override
public void onAttach(Context context) {
super.onAttach(context);
}

@Override
public void onDetach() {
super.onDetach();
}
}

最佳答案

适配器addFragment丢失

    ViewPager viewPager = rootView.findViewById(R.id.viewpager);
CategoryAdapter adapter = new CategoryAdapter(getChildFragmentManager());
BlankFragment frag= new BlankFragment ();
adapter.addFragment(frag);
viewPager.setAdapter(adapter);
TabLayout tabLayout = rootView.findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);

关于java - 选项卡 fragment 不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55946374/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com