我有一个ViewPager
,想要添加Fragments。ViewPager在屏幕上显示正确,但不幸的是它没有任何内容。
我看到一些帖子中建议替换
getSupportFragmentManager()
与
getChildFragmentManager()
但是我需要 ActionBar
。不幸的是,在 AppCompatActivity
中无法使用 ChildFragmentmanager
。
在调试过程中,我意识到 Fragment 的 onCreateView()
方法被调用并返回了一个布局。
问题:如何使 Fragments
可见?我的代码与 示例 有什么主要区别?
Activity:
public class ViewPagerActivity extends AppCompatActivity {
private ViewPager mViewPager;
private List<Location> locationList = new ArrayList<>();
private locationsBaseHandler db;
private CustomPagerAdapter mAdapter;
private Location mLocation;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_viewpager);
locationList.add(someData);
mViewPager = (ViewPager) findViewById(R.id.viewpager);
mAdapter = new CustomPagerAdapter(this, getSupportFragmentManager(), locationList);
mViewPager.setAdapter(mAdapter);
}
}
分页适配器:
public class CustomPagerAdapter extends FragmentPagerAdapter {
private Context mContext;
private List<Location> locationList = new ArrayList<>();
public CustomPagerAdapter(Context mContext, FragmentManager fm, List<Location> locationList) {
super(fm);
this.locationList.addAll(locationList);
this.mContext = mContext;
}
@Override
public Fragment getItem(int position) {
return LocationFragment.newInstance(position);
}
@Override
public int getCount() {
return 5;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return false;
}
}
片段:
public class LocationFragment extends Fragment {
private static final String ARG_LAYOUT_ID = "page_number";
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View layout = inflater.inflate(R.layout.fragment_location, container, false);
return layout;
}
public static LocationFragment newInstance(int selectedIdForIndex) {
LocationFragment fragment = new LocationFragment();
Bundle args = new Bundle();
args.putInt(ARG_LAYOUT_ID, selectedIdForIndex);
fragment.setArguments(args);
return fragment;
}
public int getPageNumber() {
return getArguments().getInt(ARG_LAYOUT_ID);
}
}