gpt4 book ai didi

android - onPageSelected 不适用于第一页

转载 作者:IT王子 更新时间:2023-10-28 23:43:40 26 4
gpt4 key购买 nike

我的寻呼机适配器(扩展 PagerAdepter)中有一个 TextView 。我用 MainActivity 的 onPageSelected 更新了这个 TextView 。其位置 > 0 的更新 TextView ,但启动页面(位置 0)不会在启动时更新。当我向前滑动然后向后滑动;它为位置 0 设置值,但我无法在开始时设置值。星页如何设置值?

public void onPageSelected(int position) {

switch (position) {
case 0:

PagerAdapter.tv.setText("value"); // => doesnt work on start

break;

default:
PagerAdapter.tv.setText("value");
break;
}
}

完整代码:

public class QuizStart extends SlidingFragmentActivity {
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

this.setContentView(R.layout.activity_main);

mPager = (ViewPager)findViewById(R.id.pager);
QuestionPagerAdapter mAdapter = new QuestionPagerAdapter();

mPager.setAdapter(mAdapter);
QuizStart.onPageSelected(0);

mPager.setOnPageChangeListener(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:

PagerAdapter.tv.setText("value"); // => doesnt work on start

break;

default:
PagerAdapter.tv.setText("value");
break;
}
}

});
}
}

最佳答案

您可以在创建 OnPageChangeListener 时手动调用 onPageSelected(0) 来设置起始状态:

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:
QuizStart.next.setText(getmycurrentpage()+"");
break;

default:

QuizStart.next.setText(getmycurrentpage()+"");
break;
}
}
});

mPager.setOnPageChangeListener(pageChangeListener);
// do this in a runnable to make sure the viewPager's views are already instantiated before triggering the onPageSelected call
mPager.post(new Runnable()
{
@Override
public void run()
{
pageChangeListener .onPageSelected(viewPager.getCurrentItem());
}
});

编辑

现在它不会得到 @metemet06

所指出的 Null Pointer exception

关于android - onPageSelected 不适用于第一页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16074058/

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