本文介绍了Android的集图像壁纸的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请告诉我如何设置图像采用Android WallpaperManager壁纸为例code。我已经缩短和编辑我的问题。希望你们能明白我的问题。我会表现出一定的尝试我做了。

HomeActivity.class

 公共类HomeActivity扩展BaseActivity {

    的String [] imageUrls;

    @覆盖
    公共无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.ac_home);
        ArrayList的<字符串> URL =新的ArrayList<字符串>();
        尝试 {
            URL URL_LINK =新的URL(http://mywebsite.net/web/thumb.xml);
            DocumentBuilderFactory的DBF = DocumentBuilderFactory.newInstance();
            DocumentBuilder的DB = dbf.newDocumentBuilder();
            文档的文档= db.parse(新的InputSource(url_link.openStream()));
            doc.getDocumentElement()归()。
            节点列表节点列表= doc.getElementsByTagName(名单);

            的for(int i = 0; I< nodeList.getLength();我++){
                节点node = nodeList.item(ⅰ);

                元素fstElmnt =(元)节点;
                节点列表名单= fstElmnt.getElementsByTagName(thumb_url);
                元件nameElement =(元件)nameList.item(0);
                名单= nameElement.getChildNodes();

                url.add(nameList.item(0).getNodeValue());
            }
            imageUrls =(字符串[])url.toArray(新的String [0]);
        }赶上(例外五){
            的System.out.println(XML帕兴Excpetion =+ E);
        }

    }
    公共无效onImageGridClick(查看视图){
        意向意图=新的意图(这一点,ImageGridActivity.class);
        intent.putExtra(Extra.IMAGES,imageUrls);
        startActivity(意向);
    }

    公共无效onImagePagerClick(查看视图){
        意向意图=新的意图(这一点,ImagePagerActivity.class);
        intent.putExtra(Extra.IMAGES,imageUrls);
        startActivity(意向);
    }
}
 

ImagePagerActivity.class

 包com.nostra13.example.universalimageloader;


进口java.io.IOException异常;


进口android.app.WallpaperManager;
进口android.graphics.Bitmap;
进口android.os.Bundle;
进口android.os.Parcelable;
进口android.support.v4.view.PagerAdapter;
进口android.support.v4.view.ViewPager;
进口android.view.LayoutInflater;
进口android.view.Menu;
进口android.view.MenuItem;
进口android.view.View;
进口android.view.animation.Animation;
进口android.view.animation.AnimationUtils;
进口android.widget.ImageView;
进口android.widget.ProgressBar;
进口android.widget.Toast;

进口com.nostra13.universalimageloader.core.DisplayImageOptions;
进口com.nostra13.universalimageloader.core.assist.FailReason;
进口com.nostra13.universalimageloader.core.assist.ImageLoadingListener;
进口com.nostra13.universalimageloader.core.assist.ImageScaleType;


公共类ImagePagerActivity扩展BaseActivity {

    私人ViewPager寻呼机;

    私人DisplayImageOptions选项;



    公共无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);

        的setContentView(R.layout.ac_image_pager);
        束束= getIntent()getExtras()。
        的String [] imageUrls = bundle.getStringArray(Extra.IMAGES);
        INT pagerPosition = bundle.getInt(Extra.IMAGE_POSITION,0);

        选项​​=新DisplayImageOptions.Builder()
            .showImageForEmptyUri(R.drawable.image_for_empty_url)
            .cacheOnDisc()
            .imageScaleType(ImageScaleType.EXACT)
            。建立();

        寻呼机=(ViewPager)findViewById(R.id.pager);
        pager.setAdapter(新ImagePagerAdapter(imageUrls));
        pager.setCurrentItem(pagerPosition);
    }

    公共无效setWallpaper(){

        WallpaperManager myWallpaperManager
         = WallpaperManager.getInstance(getApplicationContext());
        尝试 {
         myWallpaperManager.setResource(R.id.pager); // 什么都没发生
        }赶上(IOException异常E){
         // TODO自动生成的catch块
         e.printStackTrace();
        }

    }

    @覆盖
    公共布尔onCreateOptionsMenu(功能菜单){
        。getMenuInflater()膨胀(R.menu.main_menu,菜单);
        返回true;
    }

    @覆盖
    公共布尔onOptionsItemSelected(菜单项项){
        开关(item.getItemId()){
            案例R.id.item_clear_memory_cache:
                imageLoader.clearMemoryCache();
                返回true;
            案例R.id.item_clear_disc_cache:
                setWallpaper();
                返回true;
            默认:
                返回false;
        }
    }


    @覆盖
    保护无效的onStop(){
        imageLoader.stop();
        super.onStop();
    }

    私有类ImagePagerAdapter扩展PagerAdapter {

        私有String []的图像;
        私人LayoutInflater充气;

        ImagePagerAdapter(字符串[]的图像){
            this.images =图像;
            充气= getLayoutInflater();
        }

        @覆盖
        公共无效destroyItem(View容器,INT位置,Object对象){
            ((ViewPager)容器).removeView((查看)对象);
        }

        @覆盖
        公共无效finishUpdate(View容器){
        }

        @覆盖
        公众诠释getCount将(){
            返回images.length;
        }

        @覆盖
        公共对象instantiateItem(查看视图,INT位置){
            最后查看imageLayout = inflater.inflate(R.layout.item_pager_image,NULL);
            最后的ImageView ImageView的=(ImageView的)imageLayout.findViewById(R.id.image);
            最终进度微调=(进度)imageLayout.findViewById(R.id.loading);

            imageLoader.displayImage(图片[位置],ImageView的,选项,新ImageLoadingListener(){
                公共无效onLoadingStarted(){
                    spinner.setVisibility(View.VISIBLE);
                }

                公共无效onLoadingFailed(FailReason failReason){
                    字符串消息= NULL;
                    开关(failReason){
                        案例IO_ERROR:
                            消息=输入/输出错误;
                            打破;
                        案例OUT_OF_MEMORY:
                            消息=内存不足错误;
                            打破;
                        案例未知:
                            消息=未知错误;
                            打破;
                    }
                    Toast.makeText(ImagePagerActivity.this,消息,Toast.LENGTH_SHORT).show();

                    spinner.setVisibility(View.GONE);
                    imageView.setImageResource(android.R.drawable.ic_delete);
                }

                公共无效onLoadingComplete(位图loadedImage){
                    spinner.setVisibility(View.GONE);
                    动画动画= AnimationUtils.loadAnimation(ImagePagerActivity.this,R.anim.fade_in);
                    imageView.setAnimation(动画);
                    anim.start();
                }

                公共无效onLoadingCancelled(){
                    // 没做什么
                }
            });

            ((ViewPager)视图).addView(imageLayout,0);
            返回imageLayout;
        }

        @覆盖
        公共布尔isViewFromObject(查看视图,Object对象){
            返回view.equals(对象);
        }

        @覆盖
        公共无效restoreState(Parcelable状态,类加载器加载器){
        }

        @覆盖
        公共Parcelable saveState和(){
            返回null;
        }

        @覆盖
        公共无效startUpdate(View容器){
        }
    }

}
 

第一次尝试(我的 pagerPosition 是给错误pagerPosition不能被解析为一个变量)

 公共无效setWallpaper(){
             点阵位图= BitmapFactory.de codeResource(getResources(),pagerPosition);
    尝试 {
         ImagePagerActivity.this.setWallpaper(位);
            }赶上(IOException异常E){
        // TODO自动生成的catch块
        e.printStackTrace();
        }
        Log.d(库示例,图像设置好的。);
            }
 

第二尝试(我pagerPosition是给错误pagerPosition不能被解析为一个变量)

 公共无效setWallpaper(){

        尝试 {
            档案文件=新的文件(/ SD卡/ sampleimage);
            点阵位图= BitmapFactory.de codeResource(getResources(),pagerPosition);
            bitmap.com preSS(比较pressFormat.JPEG,80,新的FileOutputStream(文件));
            上下文的背景下= this.getBaseContext();
            context.setWallpaper(位);
            Toast.makeText(getApplicationContext(),墙纸已设置,Toast.LENGTH_SHORT).show();
        }赶上(MalformedURLException异常E){
            e.printStackTrace();
        }赶上(IOException异常E){
            e.printStackTrace();
        }
    }

@覆盖
        公共布尔onOptionsItemSelected(菜单项项){
            开关(item.getItemId()){
                案例R.id.set_wallpaper:
                    setWallpaper();
                    返回true;
                默认:
                    返回false;
            }
        }
 

第三尝试(我setResource(R.id.pager)没有得到来自viewpager图像。

 公共无效setWallpaper(){

        WallpaperManager myWallpaperManager
         = WallpaperManager.getInstance(getApplicationContext());
        尝试 {
         myWallpaperManager.setResource(R.id.pager);
        }赶上(IOException异常E){
         // TODO自动生成的catch块
         e.printStackTrace();
        }

}
 

结论

如果我把下面的codeS上面我的的onCreate 我的整个项目将无法运行。

 捆绑包= getIntent()getExtras()。
        的String [] imageUrls = bundle.getStringArray(Extra.IMAGES);
        最终诠释pagerPosition = bundle.getInt(Extra.IMAGE_POSITION,0);
 

解决方案

尝试下面code在ImagePagerActivity,我测试跌破code和其工作正常。

  //获取从视图中位图
公共静态位图getBitmapFromView(查看视图){
    位图returnedBitmap = Bitmap.createBitmap(view.getWidth(),查看
            .getHeight(),Bitmap.Config.ARGB_8888);
    帆布油画=新的Canvas(returnedBitmap);
    可绘制bgDrawable = view.getBackground();
    如果(bgDrawable!= NULL)
        bgDrawable.draw(画布);
    其他
        //如果我们无法获得绘制背景,然后我们将设置白色壁纸
        canvas.drawColor(Color.WHITE);
    view.draw(画布);
    返回returnedBitmap;
}

公共无效setWall(int i)以{
    WallpaperManager myWallpaperManager = WallpaperManager.getInstance(getApplicationContext());
    尝试 {
        //低于code线将设置你的当前可见寻呼机项目壁纸
        //首先我们来从可见的视图位图,然后我们就可以把它传递给壁纸
        myWallpaperManager.setBitmap(getBitmapFromView(pager.getChildAt(1)));

        //低于code线将直接设置输入流数据,以壁纸
        // myWallpaperManager.setStream(InputStream的数据);

        //低于code线将设置这是在绘制文件夹中的任何图像
        // myWallpaperManager.setResource(R.drawable.icon);
    }赶上(IOException异常E){
        e.printStackTrace();
    }
}
 

这将设置当前可见的寻呼机的项目视图(如果它是进步轮或图像)。

Please show me an example code on how to set image as wallpaper using Android WallpaperManager. I have shortened and edited my question. Hopefully you guys could understand my question. I will show some attempts I have made.

HomeActivity.class

public class HomeActivity extends BaseActivity {

    String[] imageUrls;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ac_home);
        ArrayList<String> url = new ArrayList<String>();
        try {
            URL url_link = new URL("http://mywebsite.net/web/thumb.xml");
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(new InputSource(url_link.openStream()));
            doc.getDocumentElement().normalize();
            NodeList nodeList = doc.getElementsByTagName("list");

            for (int i = 0; i < nodeList.getLength(); i++) {
                Node node = nodeList.item(i);

                Element fstElmnt = (Element)node;
                NodeList nameList = fstElmnt.getElementsByTagName("thumb_url");
                Element nameElement = (Element)nameList.item(0);
                nameList = nameElement.getChildNodes();

                url.add(nameList.item(0).getNodeValue());
            }
            imageUrls = (String[]) url.toArray(new String[0]);
        } catch (Exception e) {
            System.out.println("XML Pasing Excpetion = " + e);
        }

    }
    public void onImageGridClick(View view) {
        Intent intent = new Intent(this, ImageGridActivity.class);
        intent.putExtra(Extra.IMAGES, imageUrls);
        startActivity(intent);
    }

    public void onImagePagerClick(View view) {
        Intent intent = new Intent(this, ImagePagerActivity.class);
        intent.putExtra(Extra.IMAGES, imageUrls);
        startActivity(intent);
    }
}

ImagePagerActivity.class

package com.nostra13.example.universalimageloader;


import java.io.IOException;


import android.app.WallpaperManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;


public class ImagePagerActivity extends BaseActivity {

    private ViewPager pager;

    private DisplayImageOptions options;



    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.ac_image_pager);
        Bundle bundle = getIntent().getExtras();
        String[] imageUrls = bundle.getStringArray(Extra.IMAGES);
        int pagerPosition = bundle.getInt(Extra.IMAGE_POSITION, 0);

        options = new DisplayImageOptions.Builder()
            .showImageForEmptyUri(R.drawable.image_for_empty_url)
            .cacheOnDisc()
            .imageScaleType(ImageScaleType.EXACT)
            .build();

        pager = (ViewPager) findViewById(R.id.pager);
        pager.setAdapter(new ImagePagerAdapter(imageUrls));
        pager.setCurrentItem(pagerPosition);
    }

    public void setWallpaper() {

        WallpaperManager myWallpaperManager
         = WallpaperManager.getInstance(getApplicationContext());
        try {
         myWallpaperManager.setResource(R.id.pager); // nothing happened
        } catch (IOException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.item_clear_memory_cache:
                imageLoader.clearMemoryCache();
                return true;
            case R.id.item_clear_disc_cache:
                setWallpaper();
                return true;
            default:
                return false;
        }
    }


    @Override
    protected void onStop() {
        imageLoader.stop();
        super.onStop();
    }

    private class ImagePagerAdapter extends PagerAdapter {

        private String[] images;
        private LayoutInflater inflater;

        ImagePagerAdapter(String[] images) {
            this.images = images;
            inflater = getLayoutInflater();
        }

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

        @Override
        public void finishUpdate(View container) {
        }

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

        @Override
        public Object instantiateItem(View view, int position) {
            final View imageLayout = inflater.inflate(R.layout.item_pager_image, null);
            final ImageView imageView = (ImageView) imageLayout.findViewById(R.id.image);
            final ProgressBar spinner = (ProgressBar) imageLayout.findViewById(R.id.loading);

            imageLoader.displayImage(images[position], imageView, options, new ImageLoadingListener() {
                public void onLoadingStarted() {
                    spinner.setVisibility(View.VISIBLE);
                }

                public void onLoadingFailed(FailReason failReason) {
                    String message = null;
                    switch (failReason) {
                        case IO_ERROR:
                            message = "Input/Output error";
                            break;
                        case OUT_OF_MEMORY:
                            message = "Out Of Memory error";
                            break;
                        case UNKNOWN:
                            message = "Unknown error";
                            break;
                    }
                    Toast.makeText(ImagePagerActivity.this, message, Toast.LENGTH_SHORT).show();

                    spinner.setVisibility(View.GONE);
                    imageView.setImageResource(android.R.drawable.ic_delete);
                }

                public void onLoadingComplete(Bitmap loadedImage) {
                    spinner.setVisibility(View.GONE);
                    Animation anim = AnimationUtils.loadAnimation(ImagePagerActivity.this, R.anim.fade_in);
                    imageView.setAnimation(anim);
                    anim.start();
                }

                public void onLoadingCancelled() {
                    // Do nothing
                }
            });

            ((ViewPager) view).addView(imageLayout, 0);
            return imageLayout;
        }

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

        @Override
        public void restoreState(Parcelable state, ClassLoader loader) {
        }

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

        @Override
        public void startUpdate(View container) {
        }
    }

}

1st Attempt (My pagerPosition is giving error "pagerPosition cannot be resolved to a variable")

public void setWallpaper(){
             Bitmap bitmap = BitmapFactory.decodeResource(getResources(), pagerPosition);
    try {
         ImagePagerActivity.this.setWallpaper(bitmap);
            } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        }
        Log.d("Gallery Example", "Image setted.");
            }

2nd Attempt (My pagerPosition is giving error "pagerPosition cannot be resolved to a variable")

public void setWallpaper() {

        try {
            File file = new File("/sdcard/sampleimage");
            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), pagerPosition);
            bitmap.compress(CompressFormat.JPEG, 80, new FileOutputStream(file));
            Context context = this.getBaseContext();
            context.setWallpaper(bitmap);
            Toast.makeText(getApplicationContext(), "Wallpaper has been set", Toast.LENGTH_SHORT).show();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

@Override
        public boolean onOptionsItemSelected(MenuItem item) {
            switch (item.getItemId()) {
                case R.id.set_wallpaper:
                    setWallpaper();
                    return true;
                default:
                    return false;
            }
        }

3rd Attempt (My setResource(R.id.pager) is not getting the image from the viewpager.

public void setWallpaper() {

        WallpaperManager myWallpaperManager
         = WallpaperManager.getInstance(getApplicationContext());
        try {
         myWallpaperManager.setResource(R.id.pager);
        } catch (IOException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
        }

}

Conclusion

If i put the below codes above my onCreate my whole project will not run.

        Bundle bundle = getIntent().getExtras();
        String[] imageUrls = bundle.getStringArray(Extra.IMAGES);
        final int pagerPosition = bundle.getInt(Extra.IMAGE_POSITION, 0);
解决方案

Try below code in ImagePagerActivity, i tested below code and it is working.

    // fetch bitmap from view
public static Bitmap getBitmapFromView(View view) {
    Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view
            .getHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(returnedBitmap);
    Drawable bgDrawable = view.getBackground();
    if (bgDrawable != null)
        bgDrawable.draw(canvas);
    else
        // if we unable to get background drawable then we will set white color as wallpaper
        canvas.drawColor(Color.WHITE);
    view.draw(canvas);
    return returnedBitmap;
}

public void setWall(int i) {
    WallpaperManager myWallpaperManager = WallpaperManager.getInstance(getApplicationContext());
    try {
        // below line of code will set your current visible pager item to wallpaper
        // first we have to fetch bitmap from visible view and then we can pass it to wallpaper
        myWallpaperManager.setBitmap(getBitmapFromView(pager.getChildAt(1)));

        // below line of code will set input stream data directly to wallpaper
        // myWallpaperManager.setStream(InputStream Data);

        // below line of code will set any image which is in the drawable folder
        // myWallpaperManager.setResource(R.drawable.icon);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

It will set current visible pager's item view(if it is progress wheel or image).

这篇关于Android的集图像壁纸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-27 12:35