gpt4 book ai didi

java - onCreateView() 永远不会在 Fragment 中被调用

转载 作者:行者123 更新时间:2023-12-02 02:27:13 24 4
gpt4 key购买 nike

我想构建下一个 UI:
TabLayout 带有 2 个选项卡和 2 个不同的 fragment (已解决和未解决)我在 Fragment 中的 onCreateView 从未被调用。

这里我膨胀了我的 viewPager:

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

setContentView(R.layout.activity_main);

mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);

ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);

mAdapter = new ViewPagerAdapter(getSupportFragmentManager());
mAdapter.addFragment(new UnsolvedTasksFragment());
mAdapter.addFragment(new SolvedTasksFragment());
viewPager.setAdapter(mAdapter);

mTabLayout = (TabLayout) findViewById(R.id.tabs);
mTabLayout.setupWithViewPager(viewPager);

mTabLayout.getTabAt(0).setText(getString(R.string.tablayout_unsolved));
mTabLayout.getTabAt(1).setText(getString(R.string.tablayout_solved));

}

我的自定义 ViewPagerAdapter:

 public class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();

public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}

@Override
public Fragment getItem(int position) {
if (!mFragmentList.isEmpty() && mFragmentList.size() > id)
return mFragmentList.get(position);
return new Fragment();
}

@Override
public int getCount() {
return mFragmentList.size();
}

public void addFragment(Fragment fragment) {
mFragmentList.add(fragment);
}

@Override
public CharSequence getPageTitle(int position) {
return null;
}
}

这是我的 fragment 的示例:

 public class SolvedTasksFragment extends Fragment implements RecyclerViewClickListenerSolved {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//Some code here;
return rootView;
}

@Override
public void itemClick(View v, int position) {
}
}

也许有人可以看出出了什么问题。
我不需要整个解决方案。

最佳答案

首先设置适配器,然后添加 fragment 。像这样做。更改这些语句

    mAdapter = new ViewPagerAdapter(getSupportFragmentManager());
mAdapter.addFragment(new UnsolvedTasksFragment());
mAdapter.addFragment(new SolvedTasksFragment());
viewPager.setAdapter(mAdapter);

对于这些

mAdapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
mAdapter.addFragment(new UnsolvedTasksFragment());
mAdapter.addFragment(new SolvedTasksFragment());

关于java - onCreateView() 永远不会在 Fragment 中被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47634142/

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