Example usage for android.graphics Bitmap recycle

List of usage examples for android.graphics Bitmap recycle

Introduction

In this page you can find the example usage for android.graphics Bitmap recycle.

Prototype

public void recycle() 

Source Link

Document

Free the native object associated with this bitmap, and clear the reference to the pixel data.

Usage

From source file:com.aujur.ebookreader.activity.ReadingFragment.java

private Bitmap getBookViewSnapshot() {

    try {/*from ww  w .  jav  a 2s  .  co m*/
        Bitmap bitmap = Bitmap.createBitmap(viewSwitcher.getWidth(), viewSwitcher.getHeight(),
                Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);

        bookView.layout(0, 0, viewSwitcher.getWidth(), viewSwitcher.getHeight());

        bookView.draw(canvas);

        if (config.isShowPageNumbers()) {

            /**
             * FIXME: creating an intermediate bitmap here because I can't
             * figure out how to draw the pageNumberView directly on the
             * canvas and have it show up in the right place.
             */

            Bitmap pageNumberBitmap = Bitmap.createBitmap(pageNumberView.getWidth(), pageNumberView.getHeight(),
                    Config.ARGB_8888);
            Canvas pageNumberCanvas = new Canvas(pageNumberBitmap);

            pageNumberView.layout(0, 0, pageNumberView.getWidth(), pageNumberView.getHeight());
            pageNumberView.draw(pageNumberCanvas);

            canvas.drawBitmap(pageNumberBitmap, 0, viewSwitcher.getHeight() - pageNumberView.getHeight(),
                    new Paint());

            pageNumberBitmap.recycle();

        }

        return bitmap;
    } catch (OutOfMemoryError out) {
        viewSwitcher.setBackgroundColor(config.getBackgroundColor());
    }

    return null;
}

From source file:com.android.leanlauncher.Workspace.java

public void beginDragShared(View child, DragSource source) {
    child.clearFocus();/*from   ww  w . j  a va  2 s. co  m*/
    child.setPressed(false);

    // The outline is used to visualize where the item will land if dropped
    mDragOutline = createDragOutline(child, DRAG_BITMAP_PADDING);

    mLauncher.onDragStarted(child);
    // The drag bitmap follows the touch point around on the screen
    AtomicInteger padding = new AtomicInteger(DRAG_BITMAP_PADDING);
    final Bitmap b = createDragBitmap(child, padding);

    final int bmpWidth = b.getWidth();
    final int bmpHeight = b.getHeight();

    float scale = mLauncher.getDragLayer().getLocationInDragLayer(child, mTempXY);
    int dragLayerX = Math.round(mTempXY[0] - (bmpWidth - scale * child.getWidth()) / 2);
    int dragLayerY = Math.round(mTempXY[1] - (bmpHeight - scale * bmpHeight) / 2 - padding.get() / 2);

    LauncherAppState app = LauncherAppState.getInstance();
    DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
    Point dragVisualizeOffset = null;
    Rect dragRect = null;
    if (child instanceof BubbleTextView) {
        int iconSize = grid.iconSizePx;
        int top = child.getPaddingTop();
        int left = (bmpWidth - iconSize) / 2;
        int right = left + iconSize;
        int bottom = top + iconSize;
        dragLayerY += top;
        // Note: The drag region is used to calculate drag layer offsets, but the
        // dragVisualizeOffset in addition to the dragRect (the size) to position the outline.
        dragVisualizeOffset = new Point(-padding.get() / 2, padding.get() / 2);
        dragRect = new Rect(left, top, right, bottom);
    }

    // Clear the pressed state if necessary
    if (child instanceof BubbleTextView) {
        BubbleTextView icon = (BubbleTextView) child;
        icon.clearPressedBackground();
    }

    if (child.getTag() == null || !(child.getTag() instanceof ItemInfo)) {
        String msg = "Drag started with a view that has no tag set. This "
                + "will cause a crash (issue 11627249) down the line. " + "View: " + child + "  tag: "
                + child.getTag();
        throw new IllegalStateException(msg);
    }

    DragView dv = mDragController.startDrag(b, dragLayerX, dragLayerY, source, child.getTag(),
            DragController.DRAG_ACTION_MOVE, dragVisualizeOffset, dragRect, scale);
    dv.setIntrinsicIconScaleFactor(source.getIntrinsicIconScaleFactor());

    b.recycle();
}

From source file:com.aimfire.gallery.service.MovieProcessor.java

@Override
protected void onHandleIntent(Intent intent) {
    /*/*  w ww  .j a  v a  2 s.  co m*/
     * Obtain the FirebaseAnalytics instance.
     */
    mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);

    boolean[] result = new boolean[] { false, false };
    String previewPath = null;
    String thumbPath = null;
    String configPath = null;
    String convertFilePath = null;

    String exportL = MainConsts.MEDIA_3D_RAW_PATH + "L.png";
    String exportR = MainConsts.MEDIA_3D_RAW_PATH + "R.png";

    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

    Bundle extras = intent.getExtras();
    if (extras == null) {
        if (BuildConfig.DEBUG)
            Log.e(TAG, "onHandleIntent: error, wrong parameter");
        FirebaseCrash.report(new Exception("onHandleIntent: error, wrong parameter"));
        return;
    }

    String filePathL = extras.getString("lname");
    String filePathR = extras.getString("rname");
    String cvrNameNoExt = MediaScanner.getProcessedCvrName((new File(filePathL)).getName());

    if (BuildConfig.DEBUG)
        Log.d(TAG, "onHandleIntent:left file=" + filePathL + ", right file=" + filePathR);

    String creatorName = extras.getString("creator");
    String creatorPhotoUrl = extras.getString("photo");

    float scale = extras.getFloat(MainConsts.EXTRA_SCALE);

    /*
     * if left/right videos were taken using front facing camera,
     * they need to be swapped when generating sbs 
     */
    int facing = extras.getInt(MainConsts.EXTRA_FACING);
    boolean isFrontCamera = (facing == Camera.CameraInfo.CAMERA_FACING_FRONT) ? true : false;

    MediaMetadataRetriever retriever = new MediaMetadataRetriever();

    Bitmap bitmapL = null;
    Bitmap bitmapR = null;

    long frameTime = FIRST_KEYFRAME_TIME_US;
    if (BuildConfig.DEBUG)
        Log.d(TAG, "extract frame from left at " + frameTime / 1000 + "ms");

    try {
        long startUs = SystemClock.elapsedRealtimeNanos() / 1000;

        FileInputStream inputStreamL = new FileInputStream(filePathL);
        retriever.setDataSource(inputStreamL.getFD());
        inputStreamL.close();

        bitmapL = retriever.getFrameAtTime(frameTime, MediaMetadataRetriever.OPTION_CLOSEST_SYNC);

        FileInputStream inputStreamR = new FileInputStream(filePathR);
        retriever.setDataSource(inputStreamR.getFD());
        inputStreamR.close();

        bitmapR = retriever.getFrameAtTime(frameTime, MediaMetadataRetriever.OPTION_CLOSEST_SYNC);

        retriever.release();

        long stopUs = SystemClock.elapsedRealtimeNanos() / 1000;
        if (BuildConfig.DEBUG)
            Log.d(TAG, "retrieving preview frames took " + (stopUs - startUs) / 1000 + "ms");

        if ((bitmapL != null) && (bitmapR != null)) {
            saveFrame(bitmapL, exportL);
            saveFrame(bitmapR, exportR);
        } else {
            reportError(MediaScanner.getProcessedCvrPath((new File(filePathL)).getName()),
                    ERROR_EXTRACT_SYNC_FRAME_ERROR);
            return;
        }

        previewPath = MainConsts.MEDIA_3D_THUMB_PATH + cvrNameNoExt + ".jpeg";

        result = p.getInstance().f1(exportL, exportR, previewPath, scale, isFrontCamera);
    } catch (Exception ex) {
        retriever.release();
        reportError(MediaScanner.getProcessedCvrPath((new File(filePathL)).getName()),
                ERROR_EXTRACT_SYNC_FRAME_EXCEPTION);
        return;
    }

    if (!result[0]) {
        reportError(MediaScanner.getProcessedCvrPath((new File(filePathL)).getName()),
                ERROR_EXTRACT_SIMILARITY_MATRIX);

        File leftFrom = (new File(filePathL));
        File rightFrom = (new File(filePathR));
        File leftExportFrom = (new File(exportL));
        File rightExportFrom = (new File(exportR));

        if (!BuildConfig.DEBUG) {
            leftFrom.delete();
            rightFrom.delete();

            leftExportFrom.delete();
            rightExportFrom.delete();
        } else {
            File leftTo = new File(MainConsts.MEDIA_3D_DEBUG_PATH + leftFrom.getName());
            File rightTo = new File(MainConsts.MEDIA_3D_DEBUG_PATH + rightFrom.getName());

            leftFrom.renameTo(leftTo);
            rightFrom.renameTo(rightTo);

            File leftExportTo = new File(MainConsts.MEDIA_3D_DEBUG_PATH + leftExportFrom.getName());
            File rightExportTo = new File(MainConsts.MEDIA_3D_DEBUG_PATH + rightExportFrom.getName());

            leftExportFrom.renameTo(leftExportTo);
            rightExportFrom.renameTo(rightExportTo);
        }
    } else {
        double[] similarityMat = p.getInstance().g();

        String configData = similarityMat[0] + " " + similarityMat[1] + " " + similarityMat[2] + " "
                + similarityMat[3] + " " + similarityMat[4] + " " + similarityMat[5];

        if (result[1]) {
            convertFilePath = filePathR;
        } else {
            convertFilePath = filePathL;
        }

        configPath = createConfigFile(convertFilePath, configData);

        /*
         * save the thumbnail
         */
        if (bitmapL != null) {
            thumbPath = MainConsts.MEDIA_3D_THUMB_PATH + cvrNameNoExt + ".jpg";
            saveThumbnail(bitmapL, thumbPath);

            MediaScanner.insertExifInfo(thumbPath, "name=" + creatorName + "photourl=" + creatorPhotoUrl);
        }

        createZipFile(filePathL, filePathR, configPath, thumbPath, previewPath);

        /*
         * let CamcorderActivity know we are done.
         */
        reportResult(MediaScanner.getProcessedCvrPath((new File(filePathL)).getName()));
    }

    /*
     * paranoia
     */
    if (bitmapL != null) {
        bitmapL.recycle();
    }
    if (bitmapR != null) {
        bitmapR.recycle();
    }

    (new File(exportL)).delete();
    (new File(exportR)).delete();
}

From source file:com.android.launcher2.AsyncTaskCallback.java

private boolean beginDraggingWidget(View v) {
    mDraggingWidget = true;/*from w w w .j  ava  2s  .  c om*/
    // Get the widget preview as the drag representation
    ImageView image = (ImageView) v.findViewById(R.id.widget_preview);
    PendingAddItemInfo createItemInfo = (PendingAddItemInfo) v.getTag();

    // If the ImageView doesn't have a drawable yet, the widget preview hasn't been loaded and
    // we abort the drag.
    if (image.getDrawable() == null) {
        mDraggingWidget = false;
        return false;
    }

    // Compose the drag image
    Bitmap preview;
    Bitmap outline;
    float scale = 1f;
    if (createItemInfo instanceof PendingAddWidgetInfo) {
        // This can happen in some weird cases involving multi-touch. We can't start dragging
        // the widget if this is null, so we break out.
        if (mCreateWidgetInfo == null) {
            return false;
        }

        PendingAddWidgetInfo createWidgetInfo = mCreateWidgetInfo;
        createItemInfo = createWidgetInfo;
        int spanX = createItemInfo.spanX;
        int spanY = createItemInfo.spanY;
        int[] size = mLauncher.getWorkspace().estimateItemSize(spanX, spanY, createWidgetInfo, true);

        FastBitmapDrawable previewDrawable = (FastBitmapDrawable) image.getDrawable();
        float minScale = 1.25f;
        int maxWidth, maxHeight;
        maxWidth = Math.min((int) (previewDrawable.getIntrinsicWidth() * minScale), size[0]);
        maxHeight = Math.min((int) (previewDrawable.getIntrinsicHeight() * minScale), size[1]);
        preview = getWidgetPreview(createWidgetInfo.componentName, createWidgetInfo.previewImage,
                createWidgetInfo.icon, spanX, spanY, maxWidth, maxHeight);

        // Determine the image view drawable scale relative to the preview
        float[] mv = new float[9];
        Matrix m = new Matrix();
        m.setRectToRect(new RectF(0f, 0f, (float) preview.getWidth(), (float) preview.getHeight()),
                new RectF(0f, 0f, (float) previewDrawable.getIntrinsicWidth(),
                        (float) previewDrawable.getIntrinsicHeight()),
                Matrix.ScaleToFit.START);
        m.getValues(mv);
        scale = (float) mv[0];
    } else {
        PendingAddShortcutInfo createShortcutInfo = (PendingAddShortcutInfo) v.getTag();
        Drawable icon = mIconCache.getFullResIcon(createShortcutInfo.shortcutActivityInfo);
        preview = Bitmap.createBitmap(icon.getIntrinsicWidth(), icon.getIntrinsicHeight(),
                Bitmap.Config.ARGB_8888);

        mCanvas.setBitmap(preview);
        mCanvas.save();
        renderDrawableToBitmap(icon, preview, 0, 0, icon.getIntrinsicWidth(), icon.getIntrinsicHeight());
        mCanvas.restore();
        mCanvas.setBitmap(null);
        createItemInfo.spanX = createItemInfo.spanY = 1;
    }

    // Don't clip alpha values for the drag outline if we're using the default widget preview
    boolean clipAlpha = !(createItemInfo instanceof PendingAddWidgetInfo
            && (((PendingAddWidgetInfo) createItemInfo).previewImage == 0));

    // Save the preview for the outline generation, then dim the preview
    outline = Bitmap.createScaledBitmap(preview, preview.getWidth(), preview.getHeight(), false);

    // Start the drag
    mLauncher.lockScreenOrientation();
    mLauncher.getWorkspace().onDragStartedWithItem(createItemInfo, outline, clipAlpha);
    mDragController.startDrag(image, preview, this, createItemInfo, DragController.DRAG_ACTION_COPY, null,
            scale);
    outline.recycle();
    preview.recycle();
    return true;
}

From source file:com.irccloud.android.activity.MainActivity.java

private Uri resize(Uri in) {
    Uri out = null;/*from   ww  w.  ja  v a2 s .  co m*/
    try {
        int MAX_IMAGE_SIZE = Integer
                .parseInt(PreferenceManager.getDefaultSharedPreferences(this).getString("photo_size", "1024"));
        File imageDir = new File(Environment.getExternalStorageDirectory(), "IRCCloud");
        imageDir.mkdirs();
        new File(imageDir, ".nomedia").createNewFile();

        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(IRCCloudApplication.getInstance().getApplicationContext()
                .getContentResolver().openInputStream(in), null, o);
        int scale = 1;

        if (o.outWidth < MAX_IMAGE_SIZE && o.outHeight < MAX_IMAGE_SIZE)
            return in;

        if (o.outWidth > o.outHeight) {
            if (o.outWidth > MAX_IMAGE_SIZE)
                scale = o.outWidth / MAX_IMAGE_SIZE;
        } else {
            if (o.outHeight > MAX_IMAGE_SIZE)
                scale = o.outHeight / MAX_IMAGE_SIZE;
        }

        o = new BitmapFactory.Options();
        o.inSampleSize = scale;
        Bitmap bmp = BitmapFactory.decodeStream(IRCCloudApplication.getInstance().getApplicationContext()
                .getContentResolver().openInputStream(in), null, o);

        //ExifInterface can only work on local files, so make a temporary copy on the SD card
        out = Uri.fromFile(File.createTempFile("irccloudcapture-original", ".jpg", imageDir));
        InputStream is = IRCCloudApplication.getInstance().getApplicationContext().getContentResolver()
                .openInputStream(in);
        OutputStream os = IRCCloudApplication.getInstance().getApplicationContext().getContentResolver()
                .openOutputStream(out);
        byte[] buffer = new byte[8192];
        int len;
        while ((len = is.read(buffer)) != -1) {
            os.write(buffer, 0, len);
        }
        is.close();
        os.close();

        ExifInterface exif = new ExifInterface(out.getPath());
        int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
        new File(new URI(out.toString())).delete();

        out = Uri.fromFile(File.createTempFile("irccloudcapture-resized", ".jpg", imageDir));
        if (orientation > 1) {
            Matrix matrix = new Matrix();
            switch (orientation) {
            case ExifInterface.ORIENTATION_ROTATE_90:
                matrix.postRotate(90);
                break;
            case ExifInterface.ORIENTATION_ROTATE_180:
                matrix.postRotate(180);
                break;
            case ExifInterface.ORIENTATION_ROTATE_270:
                matrix.postRotate(270);
                break;
            }
            try {
                Bitmap oldbmp = bmp;
                bmp = Bitmap.createBitmap(oldbmp, 0, 0, oldbmp.getWidth(), oldbmp.getHeight(), matrix, true);
                oldbmp.recycle();
            } catch (OutOfMemoryError e) {
                Log.e("IRCCloud", "Out of memory rotating the photo, it may look wrong on imgur");
            }
        }

        if (bmp == null || !bmp.compress(android.graphics.Bitmap.CompressFormat.JPEG, 90, IRCCloudApplication
                .getInstance().getApplicationContext().getContentResolver().openOutputStream(out))) {
            out = null;
        }
        if (bmp != null)
            bmp.recycle();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        Crashlytics.logException(e);
    } catch (OutOfMemoryError e) {
        Log.e("IRCCloud", "Out of memory rotating the photo, it may look wrong on imgur");
    }
    if (!PreferenceManager.getDefaultSharedPreferences(this).getBoolean("keep_photos", false)
            && in.toString().contains("irccloudcapture")) {
        try {
            new File(new URI(in.toString())).delete();
        } catch (Exception e) {
        }
    }
    if (out != null)
        return out;
    else
        return in;
}

From source file:com.irccloud.android.activity.MainActivity.java

@SuppressLint("NewApi")
@SuppressWarnings({ "deprecation", "unchecked" })
@Override/*  w  w  w  .  j  a v a2s .  c  om*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    suggestionsTimer = new Timer("suggestions-timer");
    countdownTimer = new Timer("messsage-countdown-timer");

    IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
    filter.addAction(Intent.ACTION_SCREEN_OFF);
    registerReceiver(screenReceiver, filter);

    if (Build.VERSION.SDK_INT >= 21) {
        Bitmap cloud = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
        if (cloud != null) {
            setTaskDescription(new ActivityManager.TaskDescription(getResources().getString(R.string.app_name),
                    cloud, 0xFFF2F7FC));
            cloud.recycle();
        }
    }
    setContentView(R.layout.activity_message);
    try {
        setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
    } catch (Throwable t) {
    }

    suggestionsAdapter = new SuggestionsAdapter();
    progressBar = (ProgressBar) findViewById(R.id.progress);
    errorMsg = (TextView) findViewById(R.id.errorMsg);
    buffersListView = findViewById(R.id.BuffersList);
    messageContainer = (LinearLayout) findViewById(R.id.messageContainer);
    drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);

    redColor = getResources().getColor(R.color.highlight_red);
    blueColor = getResources().getColor(R.color.dark_blue);

    messageTxt = (ActionEditText) findViewById(R.id.messageTxt);
    messageTxt.setOnKeyListener(new OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (sendBtn.isEnabled()
                    && NetworkConnection.getInstance().getState() == NetworkConnection.STATE_CONNECTED
                    && event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER
                    && messageTxt.getText() != null && messageTxt.getText().length() > 0) {
                sendBtn.setEnabled(false);
                new SendTask().execute((Void) null);
            } else if (keyCode == KeyEvent.KEYCODE_TAB) {
                if (event.getAction() == KeyEvent.ACTION_DOWN)
                    nextSuggestion();
                return true;
            }
            return false;
        }
    });
    messageTxt.setOnFocusChangeListener(new OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (drawerLayout != null && v == messageTxt && hasFocus) {
                drawerLayout.closeDrawers();
                update_suggestions(false);
            } else if (!hasFocus) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        suggestionsContainer.setVisibility(View.INVISIBLE);
                    }
                });
            }
        }
    });
    messageTxt.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (drawerLayout != null) {
                drawerLayout.closeDrawers();
            }
        }
    });
    messageTxt.setOnEditorActionListener(new OnEditorActionListener() {
        public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
            if (sendBtn.isEnabled()
                    && NetworkConnection.getInstance().getState() == NetworkConnection.STATE_CONNECTED
                    && actionId == EditorInfo.IME_ACTION_SEND && messageTxt.getText() != null
                    && messageTxt.getText().length() > 0) {
                sendBtn.setEnabled(false);
                new SendTask().execute((Void) null);
            }
            return true;
        }
    });
    textWatcher = new TextWatcher() {
        public void afterTextChanged(Editable s) {
            Object[] spans = s.getSpans(0, s.length(), Object.class);
            for (Object o : spans) {
                if (((s.getSpanFlags(o) & Spanned.SPAN_COMPOSING) != Spanned.SPAN_COMPOSING)
                        && (o.getClass() == StyleSpan.class || o.getClass() == ForegroundColorSpan.class
                                || o.getClass() == BackgroundColorSpan.class
                                || o.getClass() == UnderlineSpan.class || o.getClass() == URLSpan.class)) {
                    s.removeSpan(o);
                }
            }
            if (s.length() > 0
                    && NetworkConnection.getInstance().getState() == NetworkConnection.STATE_CONNECTED) {
                sendBtn.setEnabled(true);
                if (Build.VERSION.SDK_INT >= 11)
                    sendBtn.setAlpha(1);
            } else {
                sendBtn.setEnabled(false);
                if (Build.VERSION.SDK_INT >= 11)
                    sendBtn.setAlpha(0.5f);
            }
            String text = s.toString();
            if (text.endsWith("\t")) { //Workaround for Swype
                text = text.substring(0, text.length() - 1);
                messageTxt.setText(text);
                nextSuggestion();
            } else if (suggestionsContainer != null && suggestionsContainer.getVisibility() == View.VISIBLE) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        update_suggestions(false);
                    }
                });
            } else {
                if (suggestionsTimer != null) {
                    if (suggestionsTimerTask != null)
                        suggestionsTimerTask.cancel();
                    suggestionsTimerTask = new TimerTask() {
                        @Override
                        public void run() {
                            Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
                            update_suggestions(false);
                        }
                    };
                    suggestionsTimer.schedule(suggestionsTimerTask, 250);
                }
            }
        }

        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }
    };
    messageTxt.addTextChangedListener(textWatcher);
    sendBtn = findViewById(R.id.sendBtn);
    sendBtn.setFocusable(false);
    sendBtn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (NetworkConnection.getInstance().getState() == NetworkConnection.STATE_CONNECTED)
                new SendTask().execute((Void) null);
        }
    });

    photoBtn = findViewById(R.id.photoBtn);
    if (photoBtn != null) {
        photoBtn.setFocusable(false);
        photoBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                insertPhoto();
            }
        });
    }
    userListView = findViewById(R.id.usersListFragment);

    View v = getLayoutInflater().inflate(R.layout.actionbar_messageview, null);
    v.findViewById(R.id.actionTitleArea).setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            show_topic_popup();
        }
    });

    if (drawerLayout != null) {
        if (findViewById(R.id.usersListFragment2) == null) {
            upDrawable = new DrawerArrowDrawable(this);
            greyColor = upDrawable.getColor();
            ((Toolbar) findViewById(R.id.toolbar)).setNavigationIcon(upDrawable);
            ((Toolbar) findViewById(R.id.toolbar)).setNavigationContentDescription("Show navigation drawer");
            drawerLayout.setDrawerListener(mDrawerListener);
            if (refreshUpIndicatorTask != null)
                refreshUpIndicatorTask.cancel(true);
            refreshUpIndicatorTask = new RefreshUpIndicatorTask();
            refreshUpIndicatorTask.execute((Void) null);
        }
    }
    messageTxt.setDrawerLayout(drawerLayout);

    title = (TextView) v.findViewById(R.id.title);
    subtitle = (TextView) v.findViewById(R.id.subtitle);
    key = (ImageView) v.findViewById(R.id.key);
    getSupportActionBar().setCustomView(v);
    getSupportActionBar().setDisplayShowCustomEnabled(true);
    getSupportActionBar().setDisplayShowTitleEnabled(false);

    if (savedInstanceState != null && savedInstanceState.containsKey("cid")) {
        server = ServersDataSource.getInstance().getServer(savedInstanceState.getInt("cid"));
        buffer = BuffersDataSource.getInstance().getBuffer(savedInstanceState.getInt("bid"));
        backStack = (ArrayList<Integer>) savedInstanceState.getSerializable("backStack");
    }

    if (savedInstanceState != null && savedInstanceState.containsKey("imagecaptureuri"))
        imageCaptureURI = Uri.parse(savedInstanceState.getString("imagecaptureuri"));
    else
        imageCaptureURI = null;

    ConfigInstance config = (ConfigInstance) getLastCustomNonConfigurationInstance();
    if (config != null) {
        imgurTask = config.imgurUploadTask;
        fileUploadTask = config.fileUploadTask;
    }

    drawerLayout.setScrimColor(0);
    drawerLayout.closeDrawers();

    getSupportActionBar().setElevation(0);
}

From source file:com.cognizant.trumobi.PersonaLauncher.java

private void dismissPreview(final View v) {
    final PopupWindow window = (PopupWindow) v.getTag(R.id.TAG_PREVIEW);
    if (window != null) {
        hideDesktop(false);//from w  ww.j  a va 2  s .c  o m
        window.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @SuppressWarnings("unchecked")
            public void onDismiss() {
                ViewGroup group = (ViewGroup) v.getTag(R.id.workspace);
                int count = group.getChildCount();
                for (int i = 0; i < count; i++) {
                    ((ImageView) group.getChildAt(i)).setImageDrawable(null);
                }
                ArrayList<Bitmap> bitmaps = (ArrayList<Bitmap>) v.getTag(R.id.icon);
                for (Bitmap bitmap : bitmaps)
                    bitmap.recycle();

                v.setTag(R.id.workspace, null);
                v.setTag(R.id.icon, null);
                window.setOnDismissListener(null);
            }
        });
        window.dismiss();
        showingPreviews = false;
        mWorkspace.unlock();
        mWorkspace.invalidate();
        mDesktopLocked = false;
    }
    v.setTag(R.id.TAG_PREVIEW, null);
}

From source file:com.android.launcher2.Workspace.java

public void beginDragShared(View child, DragSource source) {
    Resources r = getResources();

    // The drag bitmap follows the touch point around on the screen
    final Bitmap b = createDragBitmap(child, new Canvas(), DRAG_BITMAP_PADDING);

    final int bmpWidth = b.getWidth();
    final int bmpHeight = b.getHeight();

    float scale = mLauncher.getDragLayer().getLocationInDragLayer(child, mTempXY);
    int dragLayerX = Math.round(mTempXY[0] - (bmpWidth - scale * child.getWidth()) / 2);
    int dragLayerY = Math.round(mTempXY[1] - (bmpHeight - scale * bmpHeight) / 2 - DRAG_BITMAP_PADDING / 2);

    Point dragVisualizeOffset = null;
    Rect dragRect = null;/* w  w w.java2s. c  o m*/
    if (child instanceof BubbleTextView || child instanceof PagedViewIcon) {
        int iconSize = r.getDimensionPixelSize(R.dimen.app_icon_size);
        int iconPaddingTop = r.getDimensionPixelSize(R.dimen.app_icon_padding_top);
        int top = child.getPaddingTop();
        int left = (bmpWidth - iconSize) / 2;
        int right = left + iconSize;
        int bottom = top + iconSize;
        dragLayerY += top;
        // Note: The drag region is used to calculate drag layer offsets, but the
        // dragVisualizeOffset in addition to the dragRect (the size) to position the outline.
        dragVisualizeOffset = new Point(-DRAG_BITMAP_PADDING / 2, iconPaddingTop - DRAG_BITMAP_PADDING / 2);
        dragRect = new Rect(left, top, right, bottom);
    } else if (child instanceof FolderIcon) {
        int previewSize = r.getDimensionPixelSize(R.dimen.folder_preview_size);
        dragRect = new Rect(0, 0, child.getWidth(), previewSize);
    }

    // Clear the pressed state if necessary
    if (child instanceof BubbleTextView) {
        BubbleTextView icon = (BubbleTextView) child;
        icon.clearPressedOrFocusedBackground();
    }

    mDragController.startDrag(b, dragLayerX, dragLayerY, source, child.getTag(),
            DragController.DRAG_ACTION_MOVE, dragVisualizeOffset, dragRect, scale);
    b.recycle();

    // Show the scrolling indicator when you pick up an item
    showScrollingIndicator(false);
}

From source file:cc.flydev.launcher.Workspace.java

public void beginDragShared(View child, DragSource source) {
    // The drag bitmap follows the touch point around on the screen
    final Bitmap b = createDragBitmap(child, new Canvas(), DRAG_BITMAP_PADDING);

    final int bmpWidth = b.getWidth();
    final int bmpHeight = b.getHeight();

    float scale = mLauncher.getDragLayer().getLocationInDragLayer(child, mTempXY);
    int dragLayerX = Math.round(mTempXY[0] - (bmpWidth - scale * child.getWidth()) / 2);
    int dragLayerY = Math.round(mTempXY[1] - (bmpHeight - scale * bmpHeight) / 2 - DRAG_BITMAP_PADDING / 2);

    LauncherAppState app = LauncherAppState.getInstance();
    DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
    Point dragVisualizeOffset = null;
    Rect dragRect = null;/*ww  w  .  j  a  v  a  2  s  . c  o m*/
    if (child instanceof BubbleTextView || child instanceof PagedViewIcon) {
        int iconSize = grid.iconSizePx;
        int top = child.getPaddingTop();
        int left = (bmpWidth - iconSize) / 2;
        int right = left + iconSize;
        int bottom = top + iconSize;
        dragLayerY += top;
        // Note: The drag region is used to calculate drag layer offsets, but the
        // dragVisualizeOffset in addition to the dragRect (the size) to position the outline.
        dragVisualizeOffset = new Point(-DRAG_BITMAP_PADDING / 2, DRAG_BITMAP_PADDING / 2);
        dragRect = new Rect(left, top, right, bottom);
    } else if (child instanceof FolderIcon) {
        int previewSize = grid.folderIconSizePx;
        dragRect = new Rect(0, child.getPaddingTop(), child.getWidth(), previewSize);
    }

    // Clear the pressed state if necessary
    if (child instanceof BubbleTextView) {
        BubbleTextView icon = (BubbleTextView) child;
        icon.clearPressedOrFocusedBackground();
    }

    mDragController.startDrag(b, dragLayerX, dragLayerY, source, child.getTag(),
            DragController.DRAG_ACTION_MOVE, dragVisualizeOffset, dragRect, scale);

    if (child.getParent() instanceof ShortcutAndWidgetContainer) {
        mDragSourceInternal = (ShortcutAndWidgetContainer) child.getParent();
    }

    b.recycle();
}