import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ViewPager pager = new ViewPager(this);
pager.setId(View.generateViewId());
pager.setAdapter(new PagerAdapter() {
@Override
public Object instantiateItem(ViewGroup container, int position) {
TextView text = new TextView(MainActivity.this);
text.setText("Normal Page");
container.addView(text);
return text;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
@Override
public int getCount() {
return 5;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
});
setContentView(pager);
}
}
執行 APP 時,載入當前頁、後一頁時,執行到 instantiateItem() 時發生錯誤:
java.lang.UnsupportedOperationException: Required method instantiateItem was not overridden
at android.support.v4.view.PagerAdapter.instantiateItem(PagerAdapter.java:175)
---
ViewPager 判斷你沒有覆寫 instantiateItem() 的方式,就是確認你是否有執行到 super.instantiateItem();
如果方法中有撰寫 super.instantiateItem(container, position) 就會引發該錯誤。
執行 APP 時,往後翻 ViewPager 幾頁後,往前翻頁執行到 destroyItem() 時發生錯誤:
java.lang.UnsupportedOperationException: Required method destroyItem was not overridden
at android.support.v4.view.PagerAdapter.destroyItem(PagerAdapter.java:192)
---
ViewPager 判斷你沒有覆寫 destroyItem() 的方式,就是確認你是否有執行到 super.destroyItem();
如果方法中有撰寫 super.destroyItem(container, position, object); 就會引發該錯誤。