当我创建我FragmentPagerAdapter
的并将页数定义为 3 时,第 1 页将有内容,第 2 页将没有内容,第 3 页将有内容。如果我将页数更改为 4 或更多,则每个页面都有内容。为什么是这样?如果我创建 2 个页面,没有内容?我错过了什么?
这是我的代码:
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
public Fragment getItem(int position) {
/*
* Here we are going to return the correct type of fragment for each
* of the pages
*/
Log.d("Position", "Default Postion: " + position);
return MainListFragment.init(position);
}
@Override
public int getCount() {
// Show 3 total pages.
return 3;
}
我意识到我所有的内容都是一样的,这没关系。这里的重点是,当我有 3 页时,只有 2 页有内容。如果我有 4 页或更多页,一切都会按预期进行。
更奇怪的是,我将输出放在 的onCreate
方法中ListFragment
,这是显示的内容,它实际上创建了所有内容,ListFragments
但并未全部显示。
编辑:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_feed);
RequestUserFeed feed = new RequestUserFeed();
feed.execute(URL);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
这是其余的代码:
public static class MainListFragment extends ListFragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
int fragNum;
public static final String ARG_SECTION_NUMBER = "section_number";
private static MainListFragment init(int val) {
MainListFragment mfl = new MainListFragment();
Bundle args = new Bundle();
args.putInt("val", val);
mfl.setArguments(args);
return mfl;
}
public MainListFragment() {
}
/**
* Retrieving this instance's number from its arguments.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("Fragment", "Fragment Created for " + getArguments().getInt("val"));
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.setting_fragment,
container, false);
return rootView;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
SettingListAdapter settingAdapter = new SettingListAdapter(
getActivity().getApplicationContext(),
R.layout.setting_item_row, MainFeedActivity.mProfileList);
ListView listView = (ListView) getActivity().findViewById(android.R.id.list);
listView.setAdapter(settingAdapter);
}
}
在当前状态下,我只会在一页上获得列表视图。如果我移动这段代码:
SettingListAdapter settingAdapter = new SettingListAdapter(
getActivity().getApplicationContext(),
R.layout.setting_item_row, MainFeedActivity.mProfileList);
ListView listView = (ListView) getActivity().findViewById(android.R.id.list);
listView.setAdapter(settingAdapter);
我会onCreateView
得到不同的结果。设置列表适配器onCreateView
将填充更多页面。我知道令人困惑,但认为值得一提。