Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/image/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 将url图像ImageView设置为墙纸_Android_Image_Imageview_Android Viewpager_Bitmapfactory - Fatal编程技术网

Android 将url图像ImageView设置为墙纸

Android 将url图像ImageView设置为墙纸,android,image,imageview,android-viewpager,bitmapfactory,Android,Image,Imageview,Android Viewpager,Bitmapfactory,我正在尝试使用上下文菜单选项将URL图像设置为墙纸 URL图像通过HTTP连接和阵列下载: 示例代码: // URL Image array String[] urls = new String[]{ "http://a.hiphotos.baidu.com/image/pic/item/3bf33a87e950352ad6465dad5143fbf2b2118b6b.jpg", "http://a.hiphotos.baidu.com/image/pic/it

我正在尝试使用上下文菜单选项将URL图像设置为墙纸

URL图像通过HTTP连接和阵列下载:

示例代码:

// URL Image array
String[] urls = new String[]{

        "http://a.hiphotos.baidu.com/image/pic/item/3bf33a87e950352ad6465dad5143fbf2b2118b6b.jpg",
        "http://a.hiphotos.baidu.com/image/pic/item/c8177f3e6709c93d002077529d3df8dcd0005440.jpg",
        "http://f.hiphotos.baidu.com/image/pic/item/7aec54e736d12f2ecc3d90f84dc2d56285356869.jpg",
        "http://e.hiphotos.baidu.com/image/pic/item/9c16fdfaaf51f3de308a87fc96eef01f3a297969.jpg",
        "http://d.hiphotos.baidu.com/image/pic/item/f31fbe096b63f624b88f7e8e8544ebf81b4ca369.jpg",
        "http://h.hiphotos.baidu.com/image/pic/item/11385343fbf2b2117c2dc3c3c88065380cd78e38.jpg",
        "http://c.hiphotos.baidu.com/image/pic/item/3801213fb80e7bec5ed8456c2d2eb9389b506b38.jpg"
};
这里是适配器&核心代码

private class MyAdapter extends PagerAdapter {

    private List<View> mList;
    private AsyncImageLoader asyncImageLoader;

    public MyAdapter(List<View> list) {
        mList = list;
        asyncImageLoader = new AsyncImageLoader();
    }

    /**
     * Return the number of views available.
     */
    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return mList.size();
    }

    /**
     * Remove a page for the given position.
     *
     * instantiateItem(View container, int position)
     * This method was deprecated in API level . Use instantiateItem(ViewGroup, int)
     */
    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        // TODO Auto-generated method stub
        container.removeView(mList.get(position));
    }

    @Override
    public boolean isViewFromObject(View arg0, Object arg1) {
        // TODO Auto-generated method stub
        return arg0==arg1;
    }

    /**
     * Create the page for the given position.
     */
    @Override
    public Object instantiateItem(final ViewGroup container, final int position) {

        Drawable cachedImage = asyncImageLoader.loadDrawable(
                urls[position], new ImageCallback() {

                    public void imageLoaded(Drawable imageDrawable,
                                            String imageUrl) {

                        View view = mList.get(position);
                        image = ((ImageView) view.findViewById(id.image));
                        image.setBackground(imageDrawable);
                        container.removeView(mList.get(position));
                        container.addView(mList.get(position));
                        // adapter.notifyDataSetChanged();

                    }
                });

        View view = mList.get(position);
        image = ((ImageView) view.findViewById(id.image));
        image.setBackground(cachedImage);
        container.removeView(mList.get(position));
        container.addView(mList.get(position));
        // adapter.notifyDataSetChanged();
        return mList.get(position);
    }
}




private class MyListener implements OnPageChangeListener{

    @Override
    public void onPageScrollStateChanged(int state) {
        // TODO Auto-generated method stub
        if (state == 0) {
            //new MyAdapter(null).notifyDataSetChanged();
        }
    }

    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onPageSelected(int position) {
        for (int i = 0; i < indicator_imgs.length; i++) {

            indicator_imgs[i].setBackgroundResource(R.drawable.indicator);

        }
        indicator_imgs[position].setBackgroundResource(R.drawable.indicator_focused);
    }
}

static class AsyncImageLoader {
    private HashMap<String, SoftReference<Drawable>> imageCache;
    public AsyncImageLoader() {
        imageCache = new HashMap<String, SoftReference<Drawable>>();
    }

    public interface ImageCallback {
        public void imageLoaded(Drawable imageDrawable, String imageUrl);
    }

    public Drawable loadDrawable(final String imageUrl,
                                 final ImageCallback imageCallback) {
        if (imageCache.containsKey(imageUrl)) {
            SoftReference<Drawable> softReference = imageCache.get(imageUrl);
            Drawable drawable = softReference.get();
            if (drawable != null) {
                imageCallback.imageLoaded(drawable, imageUrl);
                return drawable;
            }
        }

        final Handler handler = new Handler() {
            public void handleMessage(Message message) {
                imageCallback.imageLoaded((Drawable) message.obj, imageUrl);
            }
        };

        new Thread() {
            @Override
            public void run() {
                Drawable drawable = loadImageFromUrl(imageUrl);
                //
                imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
                Message message = handler.obtainMessage(0, drawable);
                handler.sendMessage(message);
            }
        }.start();
        return null;
    }
    /**
     *   (HttpClient httpUrlConnection)
     */
    public Drawable loadImageFromUrl(String url) {
        try {
            HttpClient client = new DefaultHttpClient();
            client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 1000*15);
            HttpGet get = new HttpGet(url);
            HttpResponse response;
            response = client.execute(get);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                Drawable d = Drawable.createFromStream(entity.getContent(),
                        "src");
                return d;
            } else {
                return null;
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public void clearCache() {

        if (this.imageCache.size() > 0) {
            this.imageCache.clear();
        }
    }
}
我对openRawResource有一个问题,如果我试图编译这个程序,我会在openRawResource上得到一个NullPointerException,如果我试图直接将其编码为R.id.image,它会在代码上显示一个原始资源错误,使用Android Studio,有什么建议吗


非常感谢。

我会查看网络库,比如volley。它有一个NetworkImageView,可以用更少的人工将图像从url直接加载到其中。您希望在位图中加载什么?来自drawable的图像?是的,我希望加载下载的图像,然后将其设置为墙纸或保存到SD卡,例如。我将检查凌空库谢谢
// CONTEXT MENU
private static final int sdcard=0;
private static final int wallpaper=1;
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
    menu.setHeaderTitle("Save file");
    menu.add(Menu.NONE, 0, Menu.NONE, "Save to sdcard");
    menu.add(Menu.NONE, 1, Menu.NONE, "Set as wallpaper");
}

// ACTIONS ON CONTEXT ITEM SELECTED
public boolean onContextItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case 0:
            Toast.makeText(this, "Saving..", Toast.LENGTH_LONG).show();
            break;
        case 1:
            Bitmap bitmap = BitmapFactory.decodeStream(getResources().openRawResource(+ id.view_pager));
            DisplayMetrics metrics = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(metrics);
            // get the height and width of screen
            int height = metrics.heightPixels;
            int width = metrics.widthPixels;
            WallpaperManager wallpaperManager = WallpaperManager.getInstance(this);
            try {
                wallpaperManager.setBitmap(bitmap);
                wallpaperManager.suggestDesiredDimensions(width, height);
                Toast.makeText(this, "Wallpaper Set", Toast.LENGTH_LONG).show();

            } catch (IOException e) {
                e.printStackTrace();
            }
            break;
    }
    return super.onContextItemSelected(item);
}