我有一个要向其中添加片段的ViewPager.
在屏幕上可以正确查看ViewPager,但不幸的是它没有任何内容.
我已经在posts中看到了替换建议
getSupportFragmentManager()
与
getChildFragmentManager()
但是我需要ActionBar.不幸的是,ChildFragmentmanager在AppCompatActivity中不可用.
在调试时,我意识到Fragment的onCreateView()方法被调用,并且它返回一个布局.
问题:如何使片段可见?我的代码和sample的主要区别是什么?
活动:
public class ViewPagerActivity extends AppCompatActivity {
private ViewPager mViewPager;
private List 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 locationList = new ArrayList<>();
public CustomPagerAdapter(Context mContext, FragmentManager fm, List 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);
}
}
解决方法:
尝试删除CustomPagerAdapter中的isViewFromObject方法.
@Override
public boolean isViewFromObject(View view, Object object) {
return false;
}
我们可以看到对isViewFromObject的注释:
Determines whether a page View is associated with a specific key object
as returned by {@link #instantiateItem(ViewGroup, int)}. This method is
required for a PagerAdapter to function properly.
标签:android-fragments,android-viewpager,adapter,android
来源: https://codeday.me/bug/20191026/1938770.html