我正在尝试使用上下文菜单选项将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();
}
}
}
这是我的上下文菜单代码:
// 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);
}
我遇到openRawResource
的问题,如果我尝试编译程序,我在NullPointerException
上获得openRawResource
,如果我尝试将其编码为(R.id。图片)直接显示代码上的原始资源错误,使用Android Studio,请问有什么建议吗?
非常感谢。