Example usage for android.graphics RectF offsetTo

List of usage examples for android.graphics RectF offsetTo

Introduction

In this page you can find the example usage for android.graphics RectF offsetTo.

Prototype

public void offsetTo(float newLeft, float newTop) 

Source Link

Document

Offset the rectangle to a specific (left, top) position, keeping its width and height the same.

Usage

From source file:com.dynamixsoftware.printingsample.IntentApiFragment.java

@Override
public void onClick(View v) {
    switch (v.getId()) {
    case R.id.check_premium:
        new AlertDialog.Builder(requireContext()).setTitle(R.string.check_premium)
                .setMessage("" + intentApi.checkPremium()).setPositiveButton(R.string.ok, null).show();
        break;/*w ww.j  a  v  a  2s  . co m*/
    case R.id.activate_online:
        final Context appContext = requireContext().getApplicationContext();
        intentApi.setLicense("YOUR_ACTIVATION_KEY", new ISetLicenseCallback.Stub() {
            @Override
            public void start() {
                toastInMainThread(appContext, "activate start");
            }

            @Override
            public void serverCheck() {
                toastInMainThread(appContext, "activate check server");
            }

            @Override
            public void finish(final Result arg0) {
                toastInMainThread(appContext, "activate finish " + (arg0 == Result.OK ? "ok" : "error"));
            }
        });
        break;
    case R.id.setup_printer:
        intentApi.setupCurrentPrinter();
        break;
    case R.id.change_options:
        intentApi.changePrinterOptions();
        break;
    case R.id.get_current_printer:
        try {
            IPrinterInfo printer = intentApi.getCurrentPrinter();
            Toast.makeText(requireContext().getApplicationContext(),
                    "current printer " + (printer != null ? printer.getName() : "null"), Toast.LENGTH_LONG)
                    .show();
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        break;
    case R.id.print_image:
        intentApi.print(Uri.parse("file://" + FilesUtils.getFilePath(requireContext(), FilesUtils.FILE_PNG)),
                "image/png", "from printing sample");
        break;
    case R.id.print_file:
        intentApi.print(Uri.parse("file://" + FilesUtils.getFilePath(requireContext(), FilesUtils.FILE_DOC)),
                "application/msword", "from printing sample");
        break;
    case R.id.show_file_preview:
        intentApi.showFilePreview(
                Uri.parse("file://" + FilesUtils.getFilePath(requireContext(), FilesUtils.FILE_DOC)),
                "application/msword", 0);
        break;
    case R.id.print_with_your_rendering:
        try {
            IDocument.Stub document = new IDocument.Stub() {

                private int thumbnailWidth;
                private int thumbnailHeight;

                @Override
                public Bitmap renderPageFragment(int arg0, Rect fragment) throws RemoteException {
                    IPrinterInfo printer = intentApi.getCurrentPrinter();
                    if (printer != null) {
                        Bitmap bitmap = Bitmap.createBitmap(fragment.width(), fragment.height(),
                                Bitmap.Config.ARGB_8888);
                        for (int i = 0; i < 3; i++)
                            try {
                                BitmapFactory.Options options = new BitmapFactory.Options();
                                options.inPreferredConfig = Bitmap.Config.ARGB_8888;
                                options.inDither = false;
                                if (i > 0) {
                                    options.inSampleSize = 1 << i;
                                }
                                Bitmap imageBMP = BitmapFactory.decodeStream(
                                        new FileInputStream(
                                                FilesUtils.getFilePath(requireContext(), FilesUtils.FILE_PNG)),
                                        null, options);
                                Paint p = new Paint();
                                int imageWidth = 0;
                                int imageHeight = 0;
                                if (imageBMP != null) {
                                    imageWidth = imageBMP.getWidth();
                                    imageHeight = imageBMP.getHeight();
                                }
                                int xDpi = printer.getPrinterContext().getHResolution();
                                int yDpi = printer.getPrinterContext().getVResolution();
                                // in dots
                                int paperWidth = printer.getPrinterContext().getPaperWidth() * xDpi / 72;
                                int paperHeight = printer.getPrinterContext().getPaperHeight() * yDpi / 72;
                                float aspectH = (float) imageHeight / (float) paperHeight;
                                float aspectW = (float) imageWidth / (float) paperWidth;
                                aspectH = aspectH > 1 ? 1 / aspectH : aspectH;
                                aspectW = aspectW > 1 ? 1 / aspectW : aspectW;
                                RectF dst = new RectF(0, 0, fragment.width() * aspectW,
                                        fragment.height() * aspectH);
                                float sLeft = 0;
                                float sTop = fragment.top * aspectH;
                                float sRight = imageWidth;
                                float sBottom = fragment.top * aspectH + fragment.bottom * aspectH;
                                RectF source = new RectF(sLeft, sTop, sRight, sBottom);
                                Canvas canvas = new Canvas(bitmap);
                                canvas.drawColor(Color.WHITE);
                                // move image to actual printing area
                                dst.offsetTo(dst.left - fragment.left, dst.top - fragment.top);
                                Matrix matrix = new Matrix();
                                matrix.setRectToRect(source, dst, Matrix.ScaleToFit.FILL);
                                canvas.drawBitmap(imageBMP, matrix, p);
                                break;
                            } catch (IOException ex) {
                                ex.printStackTrace();
                                break;
                            } catch (OutOfMemoryError ex) {
                                if (bitmap != null) {
                                    bitmap.recycle();
                                    bitmap = null;
                                }
                                continue;
                            }
                        return bitmap;
                    } else {
                        return null;
                    }
                }

                @Override
                public void initDeviceContext(IPrinterContext printerContext, int thumbnailWidth,
                        int thumbnailHeight) {
                    this.thumbnailWidth = thumbnailWidth;
                    this.thumbnailHeight = thumbnailHeight;
                }

                @Override
                public int getTotalPages() {
                    return 1;
                }

                @Override
                public String getDescription() {
                    return "PrintHand test page";
                }

                @Override
                public Bitmap getPageThumbnail(int arg0) throws RemoteException {
                    Bitmap bitmap = Bitmap.createBitmap(thumbnailWidth, thumbnailHeight,
                            Bitmap.Config.ARGB_8888);
                    for (int i = 0; i < 3; i++)
                        try {
                            BitmapFactory.Options options = new BitmapFactory.Options();
                            options.inPreferredConfig = Bitmap.Config.ARGB_8888;
                            options.inDither = false;
                            if (i > 0) {
                                options.inSampleSize = 1 << i;
                            }
                            Bitmap imageBMP = BitmapFactory.decodeStream(
                                    new FileInputStream(
                                            FilesUtils.getFilePath(requireContext(), FilesUtils.FILE_PNG)),
                                    null, options);
                            Paint p = new Paint();
                            int imageWidth = 0;
                            int imageHeight = 0;
                            if (imageBMP != null) {
                                imageWidth = imageBMP.getWidth();
                                imageHeight = imageBMP.getHeight();
                            }
                            // default
                            int paperWidth = 2481;
                            int paperHeight = 3507;
                            IPrinterInfo printer = intentApi.getCurrentPrinter();
                            if (printer != null) {
                                int xDpi = printer.getPrinterContext().getHResolution();
                                int yDpi = printer.getPrinterContext().getVResolution();
                                // in dots
                                paperWidth = printer.getPrinterContext().getPaperWidth() * xDpi / 72;
                                paperHeight = printer.getPrinterContext().getPaperHeight() * yDpi / 72;
                            }
                            float aspectW = (float) imageWidth / (float) paperWidth;
                            float aspectH = (float) imageHeight / (float) paperHeight;
                            RectF dst = new RectF(0, 0, thumbnailWidth * aspectW, thumbnailHeight * aspectH);
                            float sLeft = 0;
                            float sTop = 0;
                            float sRight = imageWidth;
                            float sBottom = imageHeight;
                            RectF source = new RectF(sLeft, sTop, sRight, sBottom);
                            Canvas canvas = new Canvas(bitmap);
                            canvas.drawColor(Color.WHITE);
                            Matrix matrix = new Matrix();
                            matrix.setRectToRect(source, dst, Matrix.ScaleToFit.FILL);
                            canvas.drawBitmap(imageBMP, matrix, p);
                            break;
                        } catch (IOException ex) {
                            ex.printStackTrace();
                            break;
                        } catch (OutOfMemoryError ex) {
                            if (bitmap != null) {
                                bitmap.recycle();
                                bitmap = null;
                            }
                            continue;
                        }
                    return bitmap;
                }
            };
            intentApi.print(document);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        break;
    case R.id.print_with_your_rendering_without_ui:
        try {
            IJob.Stub job = new IJob.Stub() {
                @Override
                public Bitmap renderPageFragment(int num, Rect fragment) throws RemoteException {
                    IPrinterInfo printer = intentApi.getCurrentPrinter();
                    if (printer != null) {
                        Bitmap bitmap = Bitmap.createBitmap(fragment.width(), fragment.height(),
                                Bitmap.Config.ARGB_8888);
                        for (int i = 0; i < 3; i++)
                            try {
                                BitmapFactory.Options options = new BitmapFactory.Options();
                                options.inPreferredConfig = Bitmap.Config.ARGB_8888;
                                options.inDither = false;
                                if (i > 0) {
                                    options.inSampleSize = 1 << i;
                                }
                                Bitmap imageBMP = BitmapFactory.decodeStream(
                                        new FileInputStream(
                                                FilesUtils.getFilePath(requireContext(), FilesUtils.FILE_PNG)),
                                        null, options);
                                Paint p = new Paint();
                                int imageWidth = 0;
                                int imageHeight = 0;
                                if (imageBMP != null) {
                                    imageWidth = imageBMP.getWidth();
                                    imageHeight = imageBMP.getHeight();
                                }
                                int xDpi = printer.getPrinterContext().getHResolution();
                                int yDpi = printer.getPrinterContext().getVResolution();
                                // in dots
                                int paperWidth = printer.getPrinterContext().getPaperWidth() * xDpi / 72;
                                int paperHeight = printer.getPrinterContext().getPaperHeight() * yDpi / 72;
                                float aspectH = (float) imageHeight / (float) paperHeight;
                                float aspectW = (float) imageWidth / (float) paperWidth;
                                RectF dst = new RectF(0, 0, fragment.width() * aspectW,
                                        fragment.height() * aspectH);
                                float sLeft = 0;
                                float sTop = fragment.top * aspectH;
                                float sRight = imageWidth;
                                float sBottom = fragment.top * aspectH + fragment.bottom * aspectH;
                                RectF source = new RectF(sLeft, sTop, sRight, sBottom);
                                Canvas canvas = new Canvas(bitmap);
                                canvas.drawColor(Color.WHITE);
                                // move image to actual printing area
                                dst.offsetTo(dst.left - fragment.left, dst.top - fragment.top);
                                Matrix matrix = new Matrix();
                                matrix.setRectToRect(source, dst, Matrix.ScaleToFit.FILL);
                                canvas.drawBitmap(imageBMP, matrix, p);
                                break;
                            } catch (IOException ex) {
                                ex.printStackTrace();
                                break;
                            } catch (OutOfMemoryError ex) {
                                if (bitmap != null) {
                                    bitmap.recycle();
                                    bitmap = null;
                                }
                                continue;
                            }
                        return bitmap;
                    } else {
                        return null;
                    }
                }

                @Override
                public int getTotalPages() {
                    return 1;
                }
            };
            intentApi.print(job, 1);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        break;
    case R.id.print_image_with_print_hand_rendering_without_ui:
        try {
            intentApi.print("PrintingSample", "image/png",
                    Uri.parse("file://" + FilesUtils.getFilePath(requireContext(), FilesUtils.FILE_PNG)));
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        break;
    case R.id.change_image_options:
        try {
            List<PrintHandOption> imageOptions = intentApi.getImagesOptions();
            changeRandomOption(imageOptions);
            intentApi.setImagesOptions(imageOptions);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        break;
    case R.id.print_file_with_print_hand_rendering_without_ui:
        try {
            intentApi.print("PrintingSample", "application/ms-word",
                    Uri.parse("file://" + FilesUtils.getFilePath(requireContext(), FilesUtils.FILE_DOC)));
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        break;
    case R.id.print_protected_file_with_print_hand_rendering_without_ui:
        try {
            intentApi.print("PrintingSample", "application/pdf",
                    Uri.parse("file://" + FilesUtils.getFilePath(requireContext(), FilesUtils.FILE_PDF)));
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        break;
    case R.id.change_files_options:
        try {
            List<PrintHandOption> fileOptions = intentApi.getFilesOptions();
            changeRandomOption(fileOptions);
            intentApi.setFilesOptions(fileOptions);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        break;
    }
}

From source file:org.getlantern.firetweet.fragment.support.UserFragment.java

@Override
public void onActivityCreated(final Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    final FragmentActivity activity = getActivity();
    setHasOptionsMenu(true);/*from  ww  w  .  j a va2 s.  com*/
    getSharedPreferences(USER_COLOR_PREFERENCES_NAME, Context.MODE_PRIVATE)
            .registerOnSharedPreferenceChangeListener(this);
    getSharedPreferences(USER_NICKNAME_PREFERENCES_NAME, Context.MODE_PRIVATE)
            .registerOnSharedPreferenceChangeListener(this);
    mLocale = getResources().getConfiguration().locale;
    mCardBackgroundColor = ThemeUtils.getCardBackgroundColor(activity);
    mProfileImageLoader = getApplication().getMediaLoaderWrapper();
    final Bundle args = getArguments();
    long accountId = -1, userId = -1;
    String screenName = null;
    if (savedInstanceState != null) {
        args.putAll(savedInstanceState);
    } else {
        accountId = args.getLong(EXTRA_ACCOUNT_ID, -1);
        userId = args.getLong(EXTRA_USER_ID, -1);
        screenName = args.getString(EXTRA_SCREEN_NAME);
    }

    Utils.setNdefPushMessageCallback(activity, new CreateNdefMessageCallback() {

        @Override
        public NdefMessage createNdefMessage(NfcEvent event) {
            final ParcelableUser user = getUser();
            if (user == null)
                return null;
            return new NdefMessage(new NdefRecord[] {
                    NdefRecord.createUri(LinkCreator.getTwitterUserLink(user.screen_name)), });
        }
    });

    activity.setEnterSharedElementCallback(new SharedElementCallback() {

        @Override
        public void onSharedElementStart(List<String> sharedElementNames, List<View> sharedElements,
                List<View> sharedElementSnapshots) {
            final int idx = sharedElementNames.indexOf(TRANSITION_NAME_PROFILE_IMAGE);
            if (idx != -1) {
                final View view = sharedElements.get(idx);
                int[] location = new int[2];
                final RectF bounds = new RectF(0, 0, view.getWidth(), view.getHeight());
                view.getLocationOnScreen(location);
                bounds.offsetTo(location[0], location[1]);
                mProfileImageView.setTransitionSource(bounds);
            }
            super.onSharedElementStart(sharedElementNames, sharedElements, sharedElementSnapshots);
        }

        @Override
        public void onSharedElementEnd(List<String> sharedElementNames, List<View> sharedElements,
                List<View> sharedElementSnapshots) {
            int idx = sharedElementNames.indexOf(TRANSITION_NAME_PROFILE_IMAGE);
            if (idx != -1) {
                final View view = sharedElements.get(idx);
                int[] location = new int[2];
                final RectF bounds = new RectF(0, 0, view.getWidth(), view.getHeight());
                view.getLocationOnScreen(location);
                bounds.offsetTo(location[0], location[1]);
                mProfileImageView.setTransitionDestination(bounds);
            }
            super.onSharedElementEnd(sharedElementNames, sharedElements, sharedElementSnapshots);
        }

    });

    ViewCompat.setTransitionName(mProfileImageView, TRANSITION_NAME_PROFILE_IMAGE);
    ViewCompat.setTransitionName(mProfileTypeView, TRANSITION_NAME_PROFILE_TYPE);
    //        ViewCompat.setTransitionName(mCardView, TRANSITION_NAME_CARD);

    mHeaderDrawerLayout.setDrawerCallback(this);

    mPagerAdapter = new SupportTabsAdapter(activity, getChildFragmentManager());

    mViewPager.setOffscreenPageLimit(3);
    mViewPager.setAdapter(mPagerAdapter);
    mPagerIndicator.setViewPager(mViewPager);
    mPagerIndicator.setTabDisplayOption(TabPagerIndicator.LABEL);

    mFollowButton.setOnClickListener(this);
    mProfileImageView.setOnClickListener(this);
    mProfileBannerView.setOnClickListener(this);
    mListedContainer.setOnClickListener(this);
    mFollowersContainer.setOnClickListener(this);
    mFriendsContainer.setOnClickListener(this);
    mRetryButton.setOnClickListener(this);
    mProfileBannerView.setOnSizeChangedListener(this);
    mProfileBannerSpace.setOnTouchListener(this);

    mProfileNameBackground.setBackgroundColor(mCardBackgroundColor);
    mProfileDetailsContainer.setBackgroundColor(mCardBackgroundColor);
    mPagerIndicator.setBackgroundColor(mCardBackgroundColor);
    mUuckyFooter.setBackgroundColor(mCardBackgroundColor);

    getUserInfo(accountId, userId, screenName, false);

    final float actionBarElevation = ThemeUtils.getSupportActionBarElevation(activity);
    ViewCompat.setElevation(mPagerIndicator, actionBarElevation);

    setupBaseActionBar();

    setupUserPages();
}

From source file:com.hippo.largeimageview.LargeImageView.java

private void adjustPosition() {
    final int wWidth = mWindowWidth;
    final int wHeight = mWindowHeight;
    if (wWidth <= 0 || wHeight <= 0) {
        return;//from w w w.  jav a 2s . c o m
    }
    final RectF dst = mDst;
    final float dWidth = dst.width();
    final float dHeight = dst.height();
    if (dWidth <= 0 || dHeight <= 0) {
        return;
    }

    if (dWidth > wWidth) {
        float fixXOffset = dst.left;
        if (fixXOffset > 0) {
            dst.left -= fixXOffset;
            dst.right -= fixXOffset;
            mRectDirty = true;
        } else if ((fixXOffset = wWidth - dst.right) > 0) {
            dst.left += fixXOffset;
            dst.right += fixXOffset;
            mRectDirty = true;
        }
    } else {
        final float left = (wWidth - dWidth) / 2;
        dst.offsetTo(left, dst.top);
        mRectDirty = true;
    }
    if (dHeight > wHeight) {
        float fixYOffset = dst.top;
        if (fixYOffset > 0) {
            dst.top -= fixYOffset;
            dst.bottom -= fixYOffset;
            mRectDirty = true;
        } else if ((fixYOffset = wHeight - dst.bottom) > 0) {
            dst.top += fixYOffset;
            dst.bottom += fixYOffset;
            mRectDirty = true;
        }
    } else {
        final float top = (wHeight - dHeight) / 2;
        dst.offsetTo(dst.left, top);
        mRectDirty = true;
    }
}

From source file:com.dynamixsoftware.printingsample.PrintServiceFragment.java

@Override
public void onClick(View v) {
    final Context appContext = requireContext().getApplicationContext();
    switch (v.getId()) {
    case R.id.set_license:
        printingSdk.setLicense("YOUR_LICENSE_HERE", new ISetLicenseCallback.Stub() {
            @Override/*from w w w  .j  a va2  s . c  o  m*/
            public void start() {
                Toast.makeText(appContext, "set license start", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void serverCheck() {
                Toast.makeText(appContext, "set license check server", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void finish(Result result) {
                Toast.makeText(appContext, "set license finish " + (result == Result.OK ? "ok" : "error"),
                        Toast.LENGTH_SHORT).show();
            }
        });
        break;
    case R.id.init_current_and_recent_printers:
        try {
            printingSdk.initRecentPrinters(new ISetupPrinterListener.Stub() {
                @Override
                public void start() {
                    toastInMainThread(appContext, "ISetupPrinterListener start");
                }

                @Override
                public void libraryPackInstallationProcess(int arg0) {
                    toastInMainThread(appContext,
                            "ISetupPrinterListener libraryPackInstallationProcess " + arg0 + " %");
                }

                @Override
                public void finish(Result arg0) {
                    toastInMainThread(appContext, "ISetupPrinterListener finish " + arg0.name());
                    if (arg0.getType().equals(ResultType.ERROR_LIBRARY_PACK_NOT_INSTALLED)) {
                        // printingSdk.setup should be called with forceInstall = true to download required drivers
                    }
                }
            });
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        break;
    case R.id.get_current_printer:
        try {
            Printer currentPrinter = printingSdk.getCurrentPrinter();
            showDialog(getString(R.string.success),
                    "Current printer:\n" + (currentPrinter != null ? currentPrinter.getName() : "null"));
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        break;
    case R.id.get_recent_printers:
        try {
            List<Printer> recentPrinters = printingSdk.getRecentPrintersList();
            String message = "";
            for (Printer printer : recentPrinters)
                message += printer.getName() + "\n";
            if (message.length() == 0)
                message = "No recent printers";
            showDialog(getString(R.string.success), message);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        break;
    case R.id.discover_wifi:
        try {
            printingSdk.startDiscoverWiFi(new IDiscoverListener.Stub() {
                @Override
                public void start() {
                    toastInMainThread(appContext, "IDiscoverListener start");
                }

                @Override
                public void printerFound(List<Printer> arg0) {
                    toastInMainThread(appContext, "IDiscoverListener printerFound");
                    discoveredPrinters.clear();
                    discoveredPrinters.addAll(arg0);
                }

                @Override
                public void finish(Result arg0) {
                    toastInMainThread(appContext, "IDiscoverListener finish " + arg0.name());
                }
            });
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        break;
    case R.id.discover_bluetooth:
        try {
            printingSdk.startDiscoverBluetooth(new IDiscoverListener.Stub() {
                @Override
                public void start() {
                    toastInMainThread(appContext, "IDiscoverListener start");
                }

                @Override
                public void printerFound(List<Printer> arg0) {
                    toastInMainThread(appContext, "IDiscoverListener printerFound");
                    discoveredPrinters.clear();
                    discoveredPrinters.addAll(arg0);
                }

                @Override
                public void finish(Result arg0) {
                    toastInMainThread(appContext, "IDiscoverListener finish " + arg0.name());
                }
            });
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        break;
    case R.id.discover_google_cloud:
        try {
            printingSdk.startDiscoverCloud("YOUR_GOOGLE_ACCOUNT_NAME", new IDiscoverCloudListener.Stub() {

                @Override
                public void start() {
                    toastInMainThread(appContext, "IDiscoverCloudListener start");
                }

                @Override
                public void showAuthorization(Intent arg0) {
                    // Launch Intent arg0 to show authorization activity
                }

                @Override
                public void printerFound(List<Printer> arg0) {
                    toastInMainThread(appContext, "IDiscoverCloudListener printerFound");
                    discoveredPrinters.clear();
                    discoveredPrinters.addAll(arg0);
                }

                @Override
                public void finish(Result arg0) {
                    toastInMainThread(appContext, "IDiscoverCloudListener finish " + arg0.name());
                }
            });
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        break;
    case R.id.discover_smb:
        try {
            discoverSmb = printingSdk.startDiscoverSmb(new IDiscoverSmbListener.Stub() {
                @Override
                public void start() {
                    toastInMainThread(appContext, "IDiscoverSmbListener start");
                }

                @Override
                public void smbFilesFound(List<SmbFile> arg0) {
                    // Show list of SMB files. This listener is used for navigation.
                    // You should call discoverSmbControl.move(arg0) to change location.
                }

                @Override
                public void showAuthorization() {
                    // You have to ask user for authorization credentials and call discoverSmbControl.login(arg0, arg1);
                }

                @Override
                public void printerFound(List<Printer> arg0) {
                    toastInMainThread(appContext, "IDiscoverSmbListener printerFound");
                    discoveredPrinters.clear();
                    discoveredPrinters.addAll(arg0);
                }

                @Override
                public void finish(Result arg0) {
                    toastInMainThread(appContext, "IDiscoverSmbListener finish " + arg0.name());
                }
            });
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        break;
    case R.id.discover_usb:
        try {
            printingSdk.startDiscoverUSB(new IDiscoverListener.Stub() {
                @Override
                public void start() {
                    toastInMainThread(appContext, "IDiscoverListener start");
                }

                @Override
                public void printerFound(List<Printer> arg0) {
                    toastInMainThread(appContext, "IDiscoverListener printerFound");
                    discoveredPrinters.clear();
                    discoveredPrinters.addAll(arg0);
                }

                @Override
                public void finish(Result arg0) {
                    toastInMainThread(appContext, "IDiscoverListener finish " + arg0.name());
                }
            });
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        break;
    case R.id.find_driver:
        if (!discoveredPrinters.isEmpty()) {
            Printer printer = discoveredPrinters.get(0);
            try {
                printingSdk.findDrivers(printer, new IFindDriversListener.Stub() {
                    @Override
                    public void start() {
                        toastInMainThread(appContext, "IFindDriversListener start");
                    }

                    @Override
                    public void finish(List<DriversSearchEntry> arg0) {
                        toastInMainThread(appContext, "IFindDriversListener finish; Found " + arg0.size()
                                + " drivers entries;" + ((arg0.size() == 0) ? "" : ""));
                        driversSearchEntries.clear();
                        driversSearchEntries.addAll(arg0);
                    }
                });
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        } else
            showDialog(getString(R.string.error), "Discover printers first");
        break;
    case R.id.get_drivers:
        if (!discoveredPrinters.isEmpty()) {
            Printer printer = discoveredPrinters.get(0);
            TransportType transportType = printer.getTransportTypes().get(0);
            if (transportType != null) {
                try {
                    printingSdk.getDriversList(printer, transportType, new IGetDriversListener.Stub() {
                        @Override
                        public void start() {
                            toastInMainThread(appContext, "IGetDriversListener start");
                        }

                        @Override
                        public void finish(List<DriverHandleEntry> arg0) {
                            toastInMainThread(appContext, "IGetDriversListener finish");
                            driverHandleEntries.clear();
                            driverHandleEntries.addAll(arg0);
                        }
                    });
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        } else
            showDialog(getString(R.string.error), "Discover printers first");
        break;
    case R.id.setup_recent_printer:
        try {
            List<Printer> printerList = printingSdk.getRecentPrintersList();
            if (!printerList.isEmpty())
                printingSdk.setup(printerList.get(0), true, new ISetupPrinterListener.Stub() {
                    @Override
                    public void start() {
                        toastInMainThread(appContext, "ISetupPrinterListener start");
                    }

                    @Override
                    public void libraryPackInstallationProcess(int arg0) {
                        toastInMainThread(appContext,
                                "ISetupPrinterListener libraryPackInstallationProcess " + arg0 + " %");
                    }

                    @Override
                    public void finish(Result arg0) {
                        toastInMainThread(appContext, "ISetupPrinterListener finish " + arg0.name());
                        if (arg0.getType().equals(ResultType.ERROR_LIBRARY_PACK_NOT_INSTALLED)) {
                            // printingSdk.setup should be called with forceInstall = true to download required drivers
                        }
                    }
                });
            else
                showDialog(getString(R.string.error), "No recent printers");
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        break;
    case R.id.setup_discovered_printer:
        if (!discoveredPrinters.isEmpty()) {
            if (!driversSearchEntries.isEmpty()) {
                Printer printer = discoveredPrinters.get(0);
                DriversSearchEntry driversSearchEntry = driversSearchEntries.get(0);
                try {
                    printingSdk.setup(printer, driversSearchEntry.getDriverHandlesList().get(0),
                            driversSearchEntry.getTransportType(), false, new ISetupPrinterListener.Stub() {
                                @Override
                                public void start() {
                                    toastInMainThread(appContext, "ISetupPrinterListener start");
                                }

                                @Override
                                public void libraryPackInstallationProcess(int arg0) {
                                    toastInMainThread(appContext,
                                            "ISetupPrinterListener libraryPackInstallationProcess " + arg0
                                                    + " %");
                                }

                                @Override
                                public void finish(Result arg0) {
                                    toastInMainThread(appContext,
                                            "ISetupPrinterListener finish " + arg0.name());
                                    if (arg0.getType().equals(ResultType.ERROR_LIBRARY_PACK_NOT_INSTALLED)) {
                                        // printingSdk.setup should be called with forceInstall = true to download required drivers
                                    }
                                }
                            });
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            } else
                showDialog(getString(R.string.error), "Find driver first");
        } else
            showDialog(getString(R.string.error), "Discover printers first");
        break;
    case R.id.change_options:
        try {
            Printer currentPrinter = printingSdk.getCurrentPrinter();
            if (currentPrinter != null) {
                List<PrinterOption> options = currentPrinter.getOptions();
                if (options.size() > 0) {
                    Random random = new Random();
                    PrinterOption option = options.get(random.nextInt(options.size()));
                    PrinterOptionValue currentValue = option.getOptionValue();
                    List<PrinterOptionValue> valuesList = option.getOptionValueList();
                    PrinterOptionValue newValue = valuesList.get(random.nextInt(valuesList.size()));
                    printingSdk.setCurrentPrinterOptionValue(option, newValue);
                    Toast.makeText(requireContext().getApplicationContext(),
                            "option " + option.getName() + " changed from " + currentValue + " to " + newValue,
                            Toast.LENGTH_LONG).show();
                }
            } else
                showDialog(getString(R.string.error), "Setup printer first");
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        break;
    case R.id.print_image:
        try {
            if (printingSdk.getCurrentPrinter() != null) {
                List<IPage> pages = new ArrayList<>();
                pages.add(new IPage() {
                    @Override
                    public Bitmap getBitmapFragment(Rect fragment) {
                        Printer printer = null;
                        try {
                            printer = printingSdk.getCurrentPrinter();
                        } catch (RemoteException e) {
                            e.printStackTrace();
                        }
                        if (printer != null) {
                            Bitmap bitmap = Bitmap.createBitmap(fragment.width(), fragment.height(),
                                    Bitmap.Config.ARGB_8888);
                            for (int i = 0; i < 3; i++)
                                try {
                                    BitmapFactory.Options options = new BitmapFactory.Options();
                                    options.inPreferredConfig = Bitmap.Config.ARGB_8888;
                                    options.inDither = false;
                                    if (i > 0) {
                                        options.inSampleSize = 1 << i;
                                    }
                                    Bitmap imageBMP = BitmapFactory.decodeStream(new FileInputStream(
                                            FilesUtils.getFilePath(requireContext(), FilesUtils.FILE_PNG)),
                                            null, options);
                                    Paint p = new Paint();
                                    int imageWidth = 0;
                                    int imageHeight = 0;
                                    if (imageBMP != null) {
                                        imageWidth = imageBMP.getWidth();
                                        imageHeight = imageBMP.getHeight();
                                    }
                                    int xDpi = printer.getContext().getHResolution();
                                    int yDpi = printer.getContext().getVResolution();
                                    // in dots
                                    int paperWidth = printer.getContext().getPaperWidth() * xDpi / 72;
                                    int paperHeight = printer.getContext().getPaperHeight() * yDpi / 72;
                                    float aspectH = (float) imageHeight / (float) paperHeight;
                                    float aspectW = (float) imageWidth / (float) paperWidth;
                                    RectF dst = new RectF(0, 0, fragment.width() * aspectW,
                                            fragment.height() * aspectH);
                                    float sLeft = 0;
                                    float sTop = fragment.top * aspectH;
                                    float sRight = imageWidth;
                                    float sBottom = fragment.top * aspectH + fragment.bottom * aspectH;
                                    RectF source = new RectF(sLeft, sTop, sRight, sBottom);
                                    Canvas canvas = new Canvas(bitmap);
                                    canvas.drawColor(Color.WHITE);
                                    // move image to actual printing area
                                    dst.offsetTo(dst.left - fragment.left, dst.top - fragment.top);
                                    Matrix matrix = new Matrix();
                                    matrix.setRectToRect(source, dst, Matrix.ScaleToFit.FILL);
                                    canvas.drawBitmap(imageBMP, matrix, p);
                                    break;
                                } catch (IOException ex) {
                                    ex.printStackTrace();
                                    break;
                                } catch (OutOfMemoryError ex) {
                                    if (bitmap != null) {
                                        bitmap.recycle();
                                        bitmap = null;
                                    }
                                    continue;
                                }
                            return bitmap;
                        } else
                            return null;
                    }
                });
                try {
                    printingSdk.print(pages, 1, new IPrintListener.Stub() {
                        @Override
                        public void startingPrintJob() {
                            toastInMainThread(appContext, "IPrintListener startingPrintJob");
                        }

                        @Override
                        public void start() {
                            toastInMainThread(appContext, "IPrintListener start");
                        }

                        @Override
                        public void sendingPage(int arg0, int arg1) {
                            toastInMainThread(appContext,
                                    "IPrintListener sendingPage " + arg0 + "; progress " + arg1 + "%");
                        }

                        @Override
                        public void preparePage(int arg0) {
                            toastInMainThread(appContext, "IPrintListener preparePage " + arg0);
                        }

                        @Override
                        public boolean needCancel() {
                            toastInMainThread(appContext, "IPrintListener needCancel");
                            // Return false if cancel needed.
                            return false;
                        }

                        @Override
                        public void finishingPrintJob() {
                            toastInMainThread(appContext, "IPrintListener finishingPrintJob");

                        }

                        @Override
                        public void finish(Result arg0, int arg1, int arg2) {
                            toastInMainThread(appContext,
                                    "IPrintListener finish Result " + arg0 + "; Result type " + arg0.getType()
                                            + "; Total pages " + arg1 + "; Pages sent " + arg2);
                        }
                    });
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            } else
                showDialog(getString(R.string.error), "You must setup printer before print");
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        break;
    }
}

From source file:org.mariotaku.twidere.fragment.support.UserFragment.java

@Override
public void onActivityCreated(final Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    final FragmentActivity activity = getActivity();
    setHasOptionsMenu(true);//from  w ww . j a va2 s .  c  om
    getSharedPreferences(USER_COLOR_PREFERENCES_NAME, Context.MODE_PRIVATE)
            .registerOnSharedPreferenceChangeListener(this);
    getSharedPreferences(USER_NICKNAME_PREFERENCES_NAME, Context.MODE_PRIVATE)
            .registerOnSharedPreferenceChangeListener(this);
    mUserColorNameManager = UserColorNameManager.getInstance(activity);
    mPreferences = SharedPreferencesWrapper.getInstance(activity, SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE,
            SharedPreferenceConstants.class);
    mNameFirst = mPreferences.getBoolean(KEY_NAME_FIRST);
    mLocale = getResources().getConfiguration().locale;
    mCardBackgroundColor = ThemeUtils.getCardBackgroundColor(activity,
            ThemeUtils.getThemeBackgroundOption(activity), ThemeUtils.getUserThemeBackgroundAlpha(activity));
    mActionBarShadowColor = 0xA0000000;
    final TwidereApplication app = TwidereApplication.getInstance(activity);
    mProfileImageLoader = app.getMediaLoaderWrapper();
    final Bundle args = getArguments();
    long accountId = -1, userId = -1;
    String screenName = null;
    if (savedInstanceState != null) {
        args.putAll(savedInstanceState);
    } else {
        accountId = args.getLong(EXTRA_ACCOUNT_ID, -1);
        userId = args.getLong(EXTRA_USER_ID, -1);
        screenName = args.getString(EXTRA_SCREEN_NAME);
    }

    Utils.setNdefPushMessageCallback(activity, new CreateNdefMessageCallback() {

        @Override
        public NdefMessage createNdefMessage(NfcEvent event) {
            final ParcelableUser user = getUser();
            if (user == null)
                return null;
            return new NdefMessage(new NdefRecord[] {
                    NdefRecord.createUri(LinkCreator.getTwitterUserLink(user.screen_name)), });
        }
    });

    activity.setEnterSharedElementCallback(new SharedElementCallback() {

        @Override
        public void onSharedElementStart(List<String> sharedElementNames, List<View> sharedElements,
                List<View> sharedElementSnapshots) {
            final int idx = sharedElementNames.indexOf(TRANSITION_NAME_PROFILE_IMAGE);
            if (idx != -1) {
                final View view = sharedElements.get(idx);
                int[] location = new int[2];
                final RectF bounds = new RectF(0, 0, view.getWidth(), view.getHeight());
                view.getLocationOnScreen(location);
                bounds.offsetTo(location[0], location[1]);
                mProfileImageView.setTransitionSource(bounds);
            }
            super.onSharedElementStart(sharedElementNames, sharedElements, sharedElementSnapshots);
        }

        @Override
        public void onSharedElementEnd(List<String> sharedElementNames, List<View> sharedElements,
                List<View> sharedElementSnapshots) {
            int idx = sharedElementNames.indexOf(TRANSITION_NAME_PROFILE_IMAGE);
            if (idx != -1) {
                final View view = sharedElements.get(idx);
                int[] location = new int[2];
                final RectF bounds = new RectF(0, 0, view.getWidth(), view.getHeight());
                view.getLocationOnScreen(location);
                bounds.offsetTo(location[0], location[1]);
                mProfileImageView.setTransitionDestination(bounds);
            }
            super.onSharedElementEnd(sharedElementNames, sharedElements, sharedElementSnapshots);
        }

    });

    ViewCompat.setTransitionName(mProfileImageView, TRANSITION_NAME_PROFILE_IMAGE);
    ViewCompat.setTransitionName(mProfileTypeView, TRANSITION_NAME_PROFILE_TYPE);
    //        ViewCompat.setTransitionName(mCardView, TRANSITION_NAME_CARD);

    mHeaderDrawerLayout.setDrawerCallback(this);

    mPagerAdapter = new SupportTabsAdapter(activity, getChildFragmentManager());

    mViewPager.setOffscreenPageLimit(3);
    mViewPager.setAdapter(mPagerAdapter);
    mPagerIndicator.setViewPager(mViewPager);
    mPagerIndicator.setTabDisplayOption(TabPagerIndicator.LABEL);
    mPagerIndicator.setOnPageChangeListener(this);

    mFollowButton.setOnClickListener(this);
    mProfileImageView.setOnClickListener(this);
    mProfileBannerView.setOnClickListener(this);
    mListedContainer.setOnClickListener(this);
    mFollowersContainer.setOnClickListener(this);
    mFriendsContainer.setOnClickListener(this);
    mHeaderErrorIcon.setOnClickListener(this);
    mProfileBannerView.setOnSizeChangedListener(this);
    mProfileBannerSpace.setOnTouchListener(this);

    mProfileNameBackground.setBackgroundColor(mCardBackgroundColor);
    mProfileDetailsContainer.setBackgroundColor(mCardBackgroundColor);
    mPagerIndicator.setBackgroundColor(mCardBackgroundColor);
    mUuckyFooter.setBackgroundColor(mCardBackgroundColor);

    final float actionBarElevation = ThemeUtils.getSupportActionBarElevation(activity);
    ViewCompat.setElevation(mPagerIndicator, actionBarElevation);

    if (activity instanceof IThemedActivity) {
        ViewSupport.setBackground(mPagerOverlay, ThemeUtils.getNormalWindowContentOverlay(activity,
                ((IThemedActivity) activity).getCurrentThemeResourceId()));
        ViewSupport.setBackground(mErrorOverlay, ThemeUtils.getNormalWindowContentOverlay(activity,
                ((IThemedActivity) activity).getCurrentThemeResourceId()));
    }

    setupBaseActionBar();
    setupUserPages();
    if (activity instanceof IThemedActivity) {
        setUiColor(((IThemedActivity) activity).getCurrentThemeColor());
    }

    getUserInfo(accountId, userId, screenName, false);
}