2016-02-29 111 views
1

我正在尝试制作一个图像分页器,它看起来像我根据所查看的所有教程做的正确,但我得到的只是一个空白屏幕。适配器的instantiateItem方法的一个断点告诉我它正在被调用,所有正确的信息都被设置到视图中,甚至可以使用滑动功能,但我仍然没有看到任何东西。这里是我的代码PagerAdapter总是返回空白

activity_photos.xml

<RelativeLayout> // I'm not including that code, irrelevant. 
<android.support.v4.view.ViewPager 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:id="@+id/imagePager" 
    android:background="@android:color/black"/> 
</RelativeLayout> 

viewpager_itemx.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
       android:orientation="vertical" 
       android:layout_width="match_parent" 
       android:layout_height="match_parent"> 

    <ImageView 
     android:layout_width="match_parent" 
     android:layout_height="0dp" 
     android:layout_weight="1" 
     android:id="@+id/imageView"/> 

    <TextView 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:id="@+id/imageLabel" 
     android:textColor="@android:color/white"/> 
</LinearLayout> 

PhotosActivity.java

final String[] images = getResources().getStringArray(R.array.tips_images); 
    final String[] labels = getResources().getStringArray(R.array.tips_text); 

    final ViewPager viewPager = (ViewPager) findViewById(R.id.imagePager); 
    final ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(PhotoTipsActivity.this, images, labels); 

    viewPager.setAdapter(viewPagerAdapter); 

最后,ViewPagerAdapter.java

公共类ViewPagerAdapter扩展PagerAdapter {

private Context context; 
private String[] images; 
private String[] labels; 

public ViewPagerAdapter(Context context, String[] images, String[] labels) { 
    this.context = context; 
    this.images = images; 
    this.labels = labels; 
} 

@Override 
public int getCount() { 
    return images.length; 
} 

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

@Override 
public Object instantiateItem(ViewGroup container, int position) { 
    final View itemView = LayoutInflater.from(context).inflate(R.layout.viewpager_item, container, false); 
    final ImageView imageView = (ImageView) itemView.findViewById(R.id.imageView); 
    final TextView imageLabel = (TextView) itemView.findViewById(R.id.imageLabel); 

    // Get drawable image. 
    final int imageId = context.getResources().getIdentifier(images[position], "drawable", context.getPackageName()); 

    imageView.setImageResource(imageId); 
    imageLabel.setText(labels[position]); 

    return itemView; 
} 

@Override 
public void destroyItem(ViewGroup container, int position, Object object) { 
    container.removeView(((LinearLayout) object)); 
} 

}

任何公然明显的原因,我没有看到我的图片?

回答

3

同样的方法destroyItem()需要从容器中删除视图,instantiateItem()需要将视图添加到容器中。

instantiateItem()返回之前,只需添加

container.addView(itemView); 

,你会在企业。

+1

不能相信我错过了! –