小弟打算在fragment中使用ViewPager,但是在创建适配器时总是为null
MyPagerAdapter adapter = new MyPagerAdapter(getChildFragmentManager());
在Activity中管理类fragment和Fragment中管理有什么区别呢?还请高人指点!以下是我的一部分代码
public class CommunicationFragment extends Fragment {
private ViewPager viewPager;
private TextView tvLine;
private LayoutParams layoutParams;
private List<Fragment> list;
private FirstFragment mFirstFragment;
private SecondFragment mSecondFragment;
private ThirdFragment mThirdFragment;
public CommunicationFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_communication, container, false);
tvLine = (TextView)view.findViewById(R.id.tvLine);
// 获取line的长度 获取手机屏幕的宽度
int width = getActivity().getWindowManager().getDefaultDisplay().getWidth();
int lineWidth = width / 3;
// 得到tvLine参数类,参数类中包含tvLine的width,height,gravity等属性
layoutParams = (LayoutParams) tvLine.getLayoutParams();
// 把屏幕宽度赋值给layoutParams.width,不要写反了
layoutParams.width = lineWidth;
// 黑条的长度就是屏幕的1/3了
tvLine.setLayoutParams(layoutParams);
// 初始化ViewPager的集合
initPager();
// 创建适配器
MyPagerAdapter adapter = new MyPagerAdapter(getActivity().getSupportFragmentManager());
// 给ViewPager设置适配器
viewPager.setAdapter(adapter);
// 给ViewPager设置监听事件
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
/**
* position:position当前ViewPager的索引值 positionOffset:表示当前Pager偏移的百分比 positionOffsetPixels:偏移了多少像素
*/
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
// 获取tvLine的左边距
layoutParams = (LayoutParams) tvLine.getLayoutParams();
// 说明它有偏移了
if (layoutParams != null && positionOffset != 0) {
layoutParams.leftMargin = (int) ((position + positionOffset) * layoutParams.width);
tvLine.setLayoutParams(layoutParams);// 具有新的layoutMargin的layoutParams
}
}
@Override
public void onPageSelected(int position) {
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
return view;
}
//设置适配器
class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int arg0) {
return list.get(arg0);
}
@Override
public int getCount() {
return list.size();
}
}
//初始化ViewPager
private void initPager() {
list = new ArrayList<Fragment>();
mFirstFragment = new FirstFragment();
mSecondFragment = new SecondFragment();
mThirdFragment = new ThirdFragment();
list.add(mFirstFragment);
list.add(mSecondFragment);
list.add(mThirdFragment);
}
}
在
Fragment
中,使用这个方法获取FragmentManager
Fragment 内部有一个
mChildFragmentManager
实例,这个实例才是管理 内部包含的 fragment 的FragmentManager