gpt4 book ai didi

java - 永远不会为第一项调用 OnPageSelected?

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:15:17 26 4
gpt4 key购买 nike

我遇到的问题是 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);
}
}

我没有与此相关的具体任务,只是想知道:

  • 这是已知问题吗?最佳解决方案是什么?

  • 它只是为了这样工作而设计的吗?

最佳答案

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);

关于java - 永远不会为第一项调用 OnPageSelected?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34677539/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com