我正在尝试首次构建一个ViewPager。我在主onCreate方法中填充了一个View的ArrayList,并将其传递给PagerAdapter的构造函数。活动成功启动,我可以看到ViewPager(或至少是它的背景),但是其中没有任何视图出现,我只看到空白背景。我尝试膨胀其他小部件中有效的布局XML,因此那里不可能存在问题。我猜测这与我编写instantiateObject方法的方式有关。无论如何,这是我的适配器:
public class StoryAdapter extends PagerAdapter {
private Context ctx;
private ViewBuilder viewBuilder;
public StoryAdapter(Context ctx, ArrayList<View> views){
this.ctx = ctx;
}
@Override
public int getCount() {
return views.size();
}
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
// TODO Auto-generated method stub
return false;
}
@Override
public Object instantiateItem(View arg0, int arg1) {
View v = views.get(arg1);
((ViewPager) arg0).addView(v);
return v;
}
@Override
public void destroyItem(View pager, int arg1, Object view) {
((ViewPager) pager).removeView((View) view);
}
}
这是我的onCreate():
public class ShowStory extends Activity {
public int totalPages;
Button backBtn;
public String text;
public ArrayList<View> views;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_story);
backBtn = (Button)findViewById(R.id.backBtn);
backBtn.setOnClickListener(new OnClickListener() {
public void onClick(View view){
Intent intent = new Intent();
setResult(RESULT_CANCELED, intent);
finish();
}
});
ViewPager vp = (ViewPager)findViewById(R.id.storyFlipper);
views = new ArrayList<View>();
View v0 = getLayoutInflater().inflate(R.layout.galleryview, null);
TextView v0t = (TextView)v0.findViewById(R.id.headline);
v0t.setText("COVER1");
View v1 = getLayoutInflater().inflate(R.layout.coverpage, null);
// TextView v1t = (TextView)findViewById(R.id.coverText);
// v1t.setText("COVER2");
View v2 = getLayoutInflater().inflate(R.layout.coverpage, null);
// TextView v2t = (TextView)findViewById(R.id.coverText);
// v2t.setText("COVER3");
views.add(v0);
views.add(v1);
views.add(v2);
StoryAdapter sa = new StoryAdapter(this, views);
vp.setAdapter(sa);
我主要是出于教育目的在做这个,这只是一个非常简单的例子。任何帮助将不胜感激!
------编辑:我尝试了你建议的方法:
@Override
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.coverpage;
break;
case 1:
resId = R.layout.coverpage;
break;
case 2:
resId = R.layout.coverpage;
break;
case 3:
resId = R.layout.coverpage;
break;
}
View view = inflater.inflate(resId, null);
((ViewPager) collection).addView(view, 0);
return view;
}
并且有相同的结果 - 我看到viewpager的空白背景,但没有视图出现