instantiateItem最初调用两次

时间:2013-06-14 11:40:14

标签: android

您好我正在使用View Pager和PagerAdapter。在PagerAdapter中,instantiateItem()'最初调用两次。

请帮我解决这个问题,例如instantiateItem()也应该只调用一次。

提前致谢。

public Object instantiateItem(View collection, int position) {
    LayoutInflater inflater = (LayoutInflater) collection.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    int resId = 0;
    switch (position) {
        case 0: {
            resId = R.layout.first_template;
            break;
        }
        case 1: {
            resId = R.layout.second_template;
            break;
        }
        case 2: {
            resId = R.layout.third_template;
            break;
        }
        case 3: 
            resId = R.layout.first_template;
            break;
    }
    View view = inflater.inflate(resId, null);
    ((ViewPager)collection).addView(view, 0);
    return view;
}

@Override
public void destroyItem(View view, int arg1, Object arg2) {
    ((ViewPager) view).removeView((View) arg2);
}

@Override
public boolean isViewFromObject(View view, Object obj) {
    return view == ((View) obj);

}

@Override
public Parcelable saveState() {
    return null;
}

@Override
public int getCount() {
    return 4;
}

public class PageViewActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_page_view);
        PageAdapter adapter = new PageAdapter();
        ViewPager myPager = (ViewPager) findViewById(R.id.viewpager);
        myPager.setAdapter(adapter);
        myPager.setCurrentItem(0);
    }
}

0 个答案:

没有答案