Viewpager位置0不能与onPageSelected(0)一起使用

时间:2013-04-18 02:02:53

标签: android android-pageradapter

我无法为起始页面(位置0)设置值

我的意思是 QuestionPagerAdapter.tv.setText(“default”)必须在MainActivity的onPageSelected(int position)案例0中起作用,但它给出了nullpoint。但它适用于位置> 0

PagerAdapter:

public class QuestionPagerAdapter extends PagerAdapter{

    public static TextView tv;

@Override
    public Object instantiateItem(View collection, int pos) {
        LayoutInflater inflater = (LayoutInflater) collection.getContext()
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View page = inflater.inflate(R.layout.page_quiz, null);

         tv = (TextView)page.findViewById(R.id.questionText);


}
}

MainActivity:

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

@Override
            public void onPageSelected(int position) {
                switch (position) {
            case 0: 
     //       QuestionPagerAdapter.tv.setText("default");  => doesnt works
                break;

                  default:
        QuestionPagerAdapter.tv.setText("default");  =>  works
                               break;

    }

2 个答案:

答案 0 :(得分:0)

由于您已将textView实例传递给AsyncTask,因此您可以使用onPreExecute()方法在任务开始执行之前设置默认值。 onPreExecute()方法在UI线程上运行,因此不应成为问题。

http://developer.android.com/reference/android/os/AsyncTask.html#onPreExecute()

答案 1 :(得分:0)

视图寻呼机的尺寸必须大于> = 2,因此请检查您的适配器的尺寸是否大于等于0,

@Override
public int getCount() {
    return 2;// a view pager has minimum 2 pages
}