ImageView和PagerAdapter

6

我希望在ViewPager的每个页面中放置图片(就像一本书)。这些图片来自一个URL列表:

我的适配器看起来是这样的:

private class MyPagerAdapter extends PagerAdapter{

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

/**
 * Create the page for the given position.  The adapter is responsible
 * for adding the view to the container given here, although it only
 * must ensure this is done by the time it returns from
 * {@link #finishUpdate()}.
 *
 * @param container The containing View in which the page will be shown.
 * @param position The page position to be instantiated.
 * @return Returns an Object representing the new page.  This does not
 * need to be a View, but can be some other container of the page.
 */
    @Override
    public Object instantiateItem(View collection, int position) {
        // Create Views
        ScrollView view = new ScrollView(cxt);
        RelativeLayout container = new RelativeLayout(cxt);
        TextView text = new TextView(cxt);
        text.setId(1);
        ImageView[] image = new ImageView[18];
        // Parameters
        LayoutParams container_params = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
        LayoutParams text_params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        LayoutParams content_params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        content_params.addRule(RelativeLayout.BELOW, text.getId());

        view.setLayoutParams(container_params);
        container.setLayoutParams(container_params);
        text.setLayoutParams(text_params);
        //image.setLayoutParams(content_params);

        // set

        for(int i = 0; i < position; i++){
            image[i] = new ImageView(cxt);
            image[i].setLayoutParams(content_params);
            createimage(image[i], list_url.get(position));
            container.addView(image[i]);
        }
        text.setText(list_url.get(position).toString());
        // add
        view.addView(container);
        container.addView(text);
        //container.addView(image);
        ((ViewPager) collection).addView(view,0);
        return view;
    }

/**
 * Remove a page for the given position.  The adapter is responsible
 * for removing the view from its container, although it only must ensure
 * this is done by the time it returns from {@link #finishUpdate()}.
 *
 * @param container The containing View from which the page will be removed.
 * @param position The page position to be removed.
 * @param object The same object that was returned by
 * {@link #instantiateItem(View, int)}.
 */
    @Override
    public void destroyItem(View collection, int position, Object view) {
            ((ViewPager) collection).removeView((ScrollView) view);
    }



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


/**
 * Called when the a change in the shown pages has been completed.  At this
 * point you must ensure that all of the pages have actually been added or
 * removed from the container as appropriate.
 * @param container The containing View which is displaying this adapter's
 * page views.
 */
    @Override
    public void finishUpdate(View arg0) {}


    @Override
    public void restoreState(Parcelable arg0, ClassLoader arg1) {}

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

    @Override
    public void startUpdate(View arg0) {}

}

我用一个异步任务来获取这些图片:

private class CreateImage extends AsyncTask<String, Void, Drawable> {
ImageView image;
public CreateImage(ImageView img) {
    image = img;
}
protected void onPreExecute() {
}

protected Drawable doInBackground(String... urls) {
    InputStream is;
    Drawable d = null ;
    try {
        is = (InputStream)new URL(urls[0]).getContent();
        d = Drawable.createFromStream(is, "Image");
        return d;
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return d;
}
protected void onPostExecute(Drawable d) {
    image.setBackgroundDrawable(d);
}
private Drawable ImageOperations(Context ctx, String url) { 
    try {
     URL imageUrl = new URL(url);
     InputStream is = (InputStream) imageUrl.getContent();
     Drawable d = Drawable.createFromStream(is, "src");
     return d;
    } catch (MalformedURLException e) {
     e.printStackTrace();
     return null;
    } catch (IOException e) {
     e.printStackTrace();
     return null;
    }
   }
}
public void createimage(ImageView img, String url){
new CreateImage(img).execute(url);
}

事实上,它根本不起作用。
3个回答

2

我以前从未使用过PagerAdapter,但我怀疑你不能在instantiateItem中返回视图,然后仅在下载资源(在AsyncTask中)之后再返回。当AsyncTask设置背景图片时,我认为已经太晚了,适配器已经返回了该视图...

你可能需要在某个时候使视图失效...


好的,这就是为什么我在onPostExecute中留下了一个Toast并且它出现了。但是我怎么才能使视图无效呢? - Tsunaze
只需使用invalidate()即可。 - rds
我尝试使视图无效,但完全没有起作用,我在Asynctask中尝试了invalidateDrawable,但也没有起作用。 - Tsunaze
1
这是你应该使无效的“Pager”。这意味着“PagerAdapter”会再次查询所有项目上的“getView()”。因此,你应该将相应的文件保留在缓存中,并同步提供它。 - rds
1
在适配器上调用notifyDatasetChanged()方法? - ernazm
我认为@rds是正确的。在instantiateItem()完成后,您无法使视图无效。在调用instantiateItem()之前,需要下载和缓存图像。 - Mark Allison

2

for(int i = 0; i < position; i++){ image[i] = new ImageView(cxt); image[i].setLayoutParams(content_params); createimage(image[i], list_url.get(position)); container.addView(image[i]); }

我认为你不需要用for循环来做这件事情。你可以看一下兼容性库中的示例。我认为它会自动实例化一个位置的项。以下是我在谷歌上找到的一个示例-

@Override
    public Object instantiateItem(View collection, int position) {
        TextView tv = new TextView(cxt);
        tv.setText("Bonjour PAUG " + position);
        tv.setTextColor(Color.WHITE);
        tv.setTextSize(30);

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

        return tv;
    }

我知道这个例子,因为它是我替换掉的一个。现在我使用了布局膨胀器来膨胀自定义视图,但仍然不起作用。 - Tsunaze

2

非常抱歉,这是我的错误,但是我无法描述的惊讶之情 -> 我没有放置权限:

<uses-permission android:name="android.permission.INTERNET"></uses-permission>

我放置了

d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicWidth());

在onPostExecute中,因为我不想图片看起来很奇怪。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接