Set Image Wallaper of ViewPager in Universal Image Loader UIL
Asked Answered
I

1

1

I am Using Nostra Universal Image Loader plugin, I would like to be able to see the currently image on the ViewPager as the Phone Wallpaper.

My code below can set the wallpaper, but its not he currently image thats is displaying on the ViewPager, it will be a image before or a image after, and sometimes a ramdom image of the Sting Array.

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

I Also try passing the currently position from the pager as : But it also dont work and crash as Java NULL point Exception

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

this was using the sample from rajpara

Inapposite answered 11/12, 2014 at 3:17 Comment(4)
instead of pager.getChildAt(i) have you tried pager.getChildAt(1) ?Sect
@Sect Yes, I try it. It does set the Wallpaper, but its not the image on the viewPager, its the image before or After.Inapposite
One Thing I dont understand is that, when you scroll on the viewPager, it will Load/orcache, 2 to 3 images. So If I select image 2. the VivPager Will load, image2, image,3 and image 1. Why is that ? But In the actuall UI only the image 2 is showingInapposite
I'll get back to you as soon as I can, I will look at my previous code, I had this issue before.Sect
S
2

Sorry for the delay power went out, I don't know if this is the right solution but it works for me, found my code btw:

I used the public Object instantiateItem

Below is my code snippet of it:

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

and in your manifest add this:

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

I used the imageview itself to get the image and get the bitmap in that imageview after that I scaled the bitmap. I hope this is what your are looking for. :)

Sect answered 11/12, 2014 at 6:24 Comment(1)
No prob. Goodluck mate. Happy Coding.Sect

© 2022 - 2024 — McMap. All rights reserved.