我想要添加片段ViewPager
。
ViewPager在屏幕上正确查看,但不幸的是它没有任何内容。
我在一些posts中看到了替换
的建议getSupportFragmentManager()
带
getChildFragmentManager()
但我需要ActionBar
。很遗憾,ChildFragmentmanager
中没有AppCompatActivity
。
调试时我已经意识到Fragment的onCreateView()
方法被调用并返回一个布局。
问题:如何让Fragments
可见?我的代码与sample的主要区别是什么?
活动:
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);
}
}
答案 0 :(得分:4)
尝试删除isViewFromObject
中的方法CustomPagerAdapter
。
@Override
public boolean isViewFromObject(View view, Object object) {
return false;
}
我们可以看到isViewFromObject
的评论:
确定页面视图是否与特定键对象关联 由{@link #instantiateItem(ViewGroup,int)}返回。这个方法是 PagerAdapter正常运行所必需的。