我有一个 ViewPager
,我想将 fragment 添加到其中。
可以在屏幕上正确查看 ViewPager,但遗憾的是它不包含任何内容。
我在一些posts中看到了建议替换
getSupportFragmentManager()
与
getChildFragmentManager()
但我需要ActionBar
。不幸的是,ChildFragmentmanager
在 AppCompatActivity
中不可用。
在调试时,我意识到调用了 Fragment 的 onCreateView()
方法并返回了一个布局。
问题如何让Fragments
可见?我的代码与 sample 的主要区别在于?
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;
}
}
fragment :
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 - fragment 在 ViewPager 中不可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39202351/