在Universal Image Loader UIL中设置ViewPager的Image Wallaper

时间:2014-12-11 03:17:53

标签: java android android-viewpager universal-image-loader wallpaper

我正在使用Nostra Universal Image Loader插件,我希望能够将ViewPager上的当前图像看作手机壁纸。

下面我的代码可以设置壁纸,但不是他当前在ViewPager上显示的图像,它将是之前的图像或之后的图像,有时是Sting阵列的ramdom图像。

public class ImagePagerFragment extends Fragment {

    public static final String TAG = ImagePagerFragment.class.getSimpleName();


    VarController vc;
    public static final int INDEX = 2;
    public String[] imageUrls;
    DisplayImageOptions options;
    ImageView imageView;
    Button buttonSetWallpaper;
    WallpaperManager wallManager;


    ViewPager pager;
    int storePosition;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i(TAG, "onCreate");

        options = new DisplayImageOptions.Builder()
                .showImageForEmptyUri(R.drawable.ic_empty)
                .showImageOnFail(R.drawable.ic_error)
                .resetViewBeforeLoading(true)
                .cacheOnDisk(true)
                //.imageScaleType(ImageScaleType.EXACTLY)
                .imageScaleType(ImageScaleType.EXACTLY_STRETCHED)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .considerExifParams(true)
                .displayer(new FadeInBitmapDisplayer(300))
                .build();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.custom_fr_image_pager, container, false);
        pager = (ViewPager) rootView.findViewById(R.id.pager);
        Log.i(TAG, "onCreateView");

        //getActivity().getSupportActionBar().show();

        // Initiates
        imageUrls = null;
        String DateTempVC = vc.readPref_HOLDER_TMP_DATA();
        wallManager = WallpaperManager.getInstance(AppApplication.getAppContext());





        buttonSetWallpaper = (Button) rootView.findViewById(R.id.buttonSetWallpaper);
        buttonSetWallpaper.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Perform action on click
                Log.d(TAG, "buttonSetWallpaper.setOnClickListener - storePosition=> " + storePosition);

                try {
                    setWall();
                } catch(Exception e){
                    e.printStackTrace();
                    Log.e(TAG, "buttonSetWallpaper.setOnClickListener > Exception => " + e);
                }

            }
        });







        pager.setAdapter(new ImageAdapter());
        pager.setCurrentItem(getArguments().getInt(Constants.Extra.IMAGE_POSITION, 0));


        return rootView;
    }//end onCreateView





    // 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() {
        //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
            wallManager.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();
            Log.e(TAG, "setWall > IOException => " + e);
        }
    }


/*  public void setWallPaper() { //--TRY 2, THIS ONE DONT WORK

Load image from array reading VC

        //Bitmap bmpImg = ((BitmapDrawable)imageView.getDrawable()).getBitmap();
        try {
            wallManager.setBitmap(loadedImage);

            Toast.makeText(getActivity(), "Wallpaper Set Successfully!!", Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            Toast.makeText(getActivity(), "Setting WallPaper Failed!!", Toast.LENGTH_SHORT).show();
        }

    }//end setWallPaper
*/


    //------------------------------------------------------------------------------------------------------
    // ImagePagerAdapter
    //------------------------------------------------------------------------------------------------------
    private class ImageAdapter extends PagerAdapter {

        private LayoutInflater inflater;

        ImageAdapter() {
            inflater = LayoutInflater.from(getActivity());
        }

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

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

        @Override
        public Object instantiateItem(ViewGroup view, final int position) {
            View imageLayout = inflater.inflate(R.layout.item_pager_image, view, false);

            assert imageLayout != null;
            imageView = (ImageView) imageLayout.findViewById(R.id.image);
            final ProgressBar spinner = (ProgressBar) imageLayout.findViewById(R.id.loading);
            storePosition = position;
            Log.v(TAG, "instantiateItem position=> " + position);

            ImageLoader.getInstance().displayImage(imageUrls[position], imageView, options, new SimpleImageLoadingListener() {
                @Override
                public void onLoadingStarted(String imageUri, View view) {
                    spinner.setVisibility(View.VISIBLE);


                    Log.i(TAG, "onLoadingStarted position=> " + position + " | Image=> " + imageUrls[position]);
                }


                @Override
                public void onLoadingFailed(String imageUri, View view, FailReason failReason) {

                    vc = new VarController(AppApplication.getAppContext());

                    String message = null;

                    switch (failReason.getType()) {
                        case IO_ERROR:
                            message = "Input/Output error";
                            break;

                        case DECODING_ERROR:
                            message = "Image can't be decoded";
                            break;

                        case NETWORK_DENIED:
                            message = "Downloads are denied";
                            break;

                        case OUT_OF_MEMORY:
                            message = "Out Of Memory error";
                            break;

                        case UNKNOWN:
                            message = "Unknown error";
                            break;
                    }

                    Log.e(TAG, "onLoadingFailed error => " + message);
                    Utils.createUserLogParseOb(getActivity(), TAG, "onLoadingFailed", message, "", vc.readCountryPref(), vc.readIMEIPref());
                    Utils.makeToast(getActivity(), getString(R.string.sorry_there_was_an_error), false);


                    spinner.setVisibility(View.GONE);
                }


                @Override
                public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                    spinner.setVisibility(View.GONE);

                    Log.w(TAG, "onLoadingComplete | " + position + " | " + loadedImage.toString() + " | " + imageUri.toLowerCase());

                }
            });

            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;
        }
    }

我也尝试将当前位置从寻呼机传递为:但它也不起作用并因为Java NULL点异常而崩溃

    buttonSetWallpaper.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // Perform action on click
            Log.d(TAG, "buttonSetWallpaper.setOnClickListener - storePosition=> " + storePosition);

            try {
                setWall(storePosition);
            } catch(Exception e){
                e.printStackTrace();
                Log.e(TAG, "buttonSetWallpaper.setOnClickListener > Exception => " + e);
            }

        }
    });

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
        wallManager.setBitmap(getBitmapFromView(pager.getChildAt(i)));

        // 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();
        Log.e(TAG, "setWall > IOException => " + e);
    }
}

这是使用rajpara

中的示例

1 个答案:

答案 0 :(得分:1)

很抱歉延迟电源耗尽,我不知道这是否是正确的解决方案,但它适用于我,发现我的代码顺便说一句:

我使用了public Object instantiateItem

以下是我的代码片段:

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

    Button makePrimBtn = (Button)imageLayout.findViewById(R.id.btnPrime);
    makePrimBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            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

                imageView.buildDrawingCache();
                Bitmap bmp = imageView.getDrawingCache();

                DisplayMetrics metrics = new DisplayMetrics();
                getWindowManager().getDefaultDisplay().getMetrics(metrics);
                int height = metrics.heightPixels;
                int width = metrics.widthPixels;
                Bitmap bitmap = Bitmap.createScaledBitmap(bmp , width, height, true);
                myWallpaperManager.setWallpaperOffsetSteps(1, 1);
                myWallpaperManager.suggestDesiredDimensions(width, height);
                myWallpaperManager.setBitmap(bitmap);

                // 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();
            }


        }
    });

    imageLoader.displayImage(images[position], imageView, options, new SimpleImageLoadingListener() {
        @Override
        public void onLoadingStarted(String imageUri, View view) {
            spinner.setVisibility(View.VISIBLE);
        }

        @Override
        public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
            String message = null;
            switch (failReason.getType()) {
                case IO_ERROR:
                    message = "Input/Output error";
                    break;
                case DECODING_ERROR:
                    message = "Image can't be decoded";
                    break;
                case NETWORK_DENIED:
                    message = "Downloads are denied";
                    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);
        }

        @Override
        public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {

        }
    });

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

并在你的清单中添加:

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

我使用了imageview本身来获取图像,然后在该图像视图中获取位图,之后我缩放了位图。我希望这是你正在寻找的。 :)