我遇到的问题是ViewPager没有为0项调用onPageSelected。 代码示例:
public class PagerActivity extends ActionBarActivity implements ViewPager.OnPageChangeListener {
private static final String TAG = PagerActivity.class.getCanonicalName();
private ViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pager);
mViewPager = (ViewPager) findViewById(R.id.view_pager);
mViewPager.setAdapter(new ViewAdapter());
mViewPager.setOnPageChangeListener(this);
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
Log.e(TAG, "position = " + position);
}
@Override
public void onPageSelected(int position) {
Log.e(TAG, "selected page = " + position);
}
@Override
public void onPageScrollStateChanged(int state) {
Log.e(TAG, "state = " + state);
}
private class ViewAdapter extends PagerAdapter {
@Override
public int getCount() {
return 5;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
ViewGroup viewGroup = (ViewGroup) LayoutInflater.from(container.getContext())
.inflate(R.layout.view_pager_item, container, false);
TextView textView = (TextView) viewGroup.findViewById(R.id.page_indicator);
textView.setText("Page position = " + position);
container.addView(viewGroup);
return viewGroup;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((ViewGroup) object);
}
}
我没有与此相关的具体任务,只是想知道:
这是一个已知问题,最佳解决方案是什么?
它只是设计为这样工作吗?
答案 0 :(得分:2)
在OnPageChangeListener
pageChangeListener.onPageSelected(0); //Set start to 0 page
在你的情况下:
PagerActivity.onPageSelected(0);
但是,您应该从课程中删除implements ViewPager.OnPageChangeListener
并添加:
OnPageChangeListener pageChangeListener = new OnPageChangeListener() {
@Override
public void onPageScrollStateChanged(int arg0) { }
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) { }
@Override
public void onPageSelected(int position) {
switch (position) {
case 0:
Log.e(TAG, "selected page = " + position);
break;
default:
Log.e(TAG, "selected page = " + position);
break;
}
}
});
mViewPager.setOnPageChangeListener(pageChangeListener);
pageChangeListener.onPageSelected(0);