PagerAdapter显示空白

时间:2015-12-03 11:20:18

标签: android

我试图添加一个显示在屏幕上的ViewPager,并允许您滑过它们,但视图都是空白的。

我在vp_image中尝试过使用静态内容,但仍然显示为空白。

vp_image.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/img"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

</RelativeLayout>

public class ProfileActivity extends Fragment {

    private ViewPager viewPager;
    private  ViewPagerAdapter viewPagerAdapter;
    public ArrayList<String> IMAGES;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.content_fragment, container, false);

        Context context = getActivity();    

        IMAGES = new ArrayList<String>();

        IMAGES.add("URL");
        IMAGES.add("URL");
        IMAGES.add("URL");    

        viewPager = (ViewPager)v.findViewById(R.id.view_pager);
        viewPagerAdapter = new ViewPagerAdapter(context,IMAGES);
        viewPager.setAdapter(viewPagerAdapter);

        return v;
    }

    public class ViewPagerAdapter extends PagerAdapter {
        private  Context context;
        private ArrayList<String> IMAGES = new ArrayList<>();

        public ViewPagerAdapter(Context context, ArrayList<String> IMAGES) {
            this.IMAGES = IMAGES;
            this.context = context;
        }

        @Override
        public int getCount() {
            return IMAGES.size();
        }

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

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

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

        @Override
        public Object instantiateItem(View collection, int position ) {

            LayoutInflater inflater = (LayoutInflater) collection.getContext()
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            View view = inflater.inflate(R.layout.vp_image,null);

            ImageView img = (ImageView) view.findViewById(R.id.img);

            Picasso.with(context).load(IMAGES.get(position)).into(img);

            ((ViewPager) collection).addView(view, 0);

            return view;
        }
    }

}

1 个答案:

答案 0 :(得分:2)

问题出在这里。

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

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

第二次改变

  ((ViewPager) collection).addView(view, 0);

  ((ViewPager) collection).addView(view);