为何我的viewpager无法在片段中工作?
作者:互联网
我的片段有以下代码.我几乎从一个基本的视图分页器示例中获取了此信息,并将其打包为一个片段,以测试我正在处理的项目.
我正在使用ACtionBarSherlock和viewPagerIndicator库.下面的片段包含一个viewPager,在本示例中,该viewPager应该在简单的标题字符串之间滑动.
我在一个活动中使用ViewPager和ViewPagerIndicator尝试了该示例,没有问题.但是第二个我把它弄成碎片. BOOM,只有黑屏…没有错误,只有黑屏…我感觉我一定是在膨胀,或者错误地访问了布局…
有任何想法吗?
这是代码:
public class TestFragment extends SherlockFragment {
//~Constants----------------------------------------------
//~Data Fields--------------------------------------------
//~Constructors--------------------------------------------
@Override
public void onCreate(Bundle savedInstanceState) {
//Setup view
super.onCreate(savedInstanceState);
View view = onCreateView(getLayoutInflater(savedInstanceState), null, savedInstanceState);
ViewPagerAdapter adapter = new ViewPagerAdapter( this.getSherlockActivity() );
ViewPager pager =
(ViewPager)view.findViewById(R.id.free_time_day_pager);
TitlePageIndicator indicator =
(TitlePageIndicator)view.findViewById(R.id.titles);
pager.setAdapter( adapter );
indicator.setViewPager( pager );
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.free_time_fragment_layout, null, false);
return view;
}
//~Methods-------------------------------------------------
}
解决方法:
不要调用错误的onCreateView.
onCreateView是一个重写的方法,由FragmentManger调用以处理Fragment的生命周期.
private ViewPager mViewPager;
private TitlePagerIndicator mIndicator;
// Called first
@Override
public void onCreate(Bundle savedInstanceState) {
//Setup view
super.onCreate(savedInstanceState);
}
// Called second
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.free_time_fragment_layout, null, false);
return view;
}
// Called third
@Override
public View onViewCreated(View v){
super.onViewCreated(v);
mViewPager = (ViewPager) v.findViewById(R.id.free_time_day_pager);
mIndicator = (TitlePageIndicator)v.findViewById(R.id.titles);
}
public void onActivityCreated(Bundle bdl){
super.onActivityCreated(bdl);
ViewPagerAdapter adapter = new ViewPagerAdapter( getSherlockActivity() );
mViewPager.setAdapter(adapter);
mIndicator.setViewPager(pager);
}
还请注意,如果您使用的是FragmentPagerAdapter,则需要一种特殊的方法来创建ViewPagerFragment,这有点棘手,但请参阅此gist.
也了解有关片段生命周期here的信息.
干杯
标签:viewpagerindicator,android-fragments,android-viewpager,actionbarsherlock,android 来源: https://codeday.me/bug/20191127/2076399.html