Example usage for android.widget ImageView setImageBitmap

List of usage examples for android.widget ImageView setImageBitmap

Introduction

In this page you can find the example usage for android.widget ImageView setImageBitmap.

Prototype

@android.view.RemotableViewMethod
public void setImageBitmap(Bitmap bm) 

Source Link

Document

Sets a Bitmap as the content of this ImageView.

Usage

From source file:com.baiiu.autoloopviewpager.loopvp.LoopViewPager.java

private void setupDummyView() {
    int childCount = getChildCount();
    ImageView dummyView = null;
    View targetView = null;// w  ww.  j  av a2  s.c om
    ItemInfo targetInfo = mItems.get(2);
    for (int i = 0; i < childCount; i++) {
        View child = getChildAt(i);
        if (child instanceof ImageView) {
            Object tag = child.getTag();
            if (tag != null && tag instanceof Integer) {
                int index = (Integer) tag;
                if (index == -1) {
                    dummyView = (ImageView) child;
                    continue;
                }
            }
        }

        if (mAdapter.isViewFromObject(child, targetInfo.object)) {
            targetView = child;
        }
    }

    if (targetView != null && dummyView != null) {
        Bitmap bitmap = getViewBitmap(targetView);
        dummyView.setImageBitmap(bitmap);
    }
}

From source file:com.google.android.apps.santatracker.rocketsleigh.RocketSleighActivity.java

private void addWoodObstacles(int screens) {
    int totalSlots = screens * SLOTS_PER_SCREEN;
    for (int i = 0; i < totalSlots;) {
        // Any given "slot" has a 1 in 3 chance of having an obstacle
        if (mRandom.nextInt(3) == 0) {
            View view = mInflater.inflate(R.layout.obstacle_layout, null);
            ImageView top = (ImageView) view.findViewById(R.id.top_view);
            ImageView bottom = (ImageView) view.findViewById(R.id.bottom_view);
            ImageView back = (ImageView) view.findViewById(R.id.back_view);

            // Which obstacle?
            int width = 0;
            //            int obstacle = mRandom.nextInt((WOOD_OBSTACLES.length/3));
            if ((mWoodObstacleIndex % 20) == 0) {
                ObstacleLoadTask task = new ObstacleLoadTask(getResources(), WOOD_OBSTACLES, mWoodObstacles,
                        mWoodObstacleList, mWoodObstacleIndex + 20, 3, mScaleX, mScaleY);
                task.execute();/*from w ww. j  a  v  a 2 s . c om*/
            }
            int obstacle = mWoodObstacleList.get(mWoodObstacleIndex++);
            if (mWoodObstacleIndex >= mWoodObstacleList.size()) {
                mWoodObstacleIndex = 0;
            }
            int topIndex = obstacle * 3;
            int bottomIndex = topIndex + 1;
            int backIndex = topIndex + 2;
            if (WOOD_OBSTACLES[backIndex] != -1) {
                Bitmap bmp = null;
                synchronized (mWoodObstacles) {
                    bmp = mWoodObstacles.get(WOOD_OBSTACLES[backIndex]);
                }
                while (bmp == null) {
                    synchronized (mWoodObstacles) {
                        bmp = mWoodObstacles.get(WOOD_OBSTACLES[backIndex]);
                        if (bmp == null) {
                            try {
                                mWoodObstacles.wait();
                            } catch (InterruptedException e) {
                            }
                        }
                    }
                }
                width = bmp.getWidth();
                back.setImageBitmap(bmp);
            } else {
                back.setVisibility(View.GONE);
            }

            int currentObstacle = 0; // Same values as mLastObstacle
            if (WOOD_OBSTACLES[topIndex] != -1) {
                currentObstacle |= 1;
                Bitmap bmp = null;
                synchronized (mWoodObstacles) {
                    bmp = mWoodObstacles.get(WOOD_OBSTACLES[topIndex]);
                }
                while (bmp == null) {
                    synchronized (mWoodObstacles) {
                        bmp = mWoodObstacles.get(WOOD_OBSTACLES[topIndex]);
                        if (bmp == null) {
                            try {
                                mWoodObstacles.wait();
                            } catch (InterruptedException e) {
                            }
                        }
                    }
                }
                width = bmp.getWidth();
                top.setImageBitmap(bmp);
            } else {
                top.setVisibility(View.GONE);
            }

            if (WOOD_OBSTACLES[bottomIndex] != -1) {
                currentObstacle |= 2;
                Bitmap bmp = null;
                synchronized (mWoodObstacles) {
                    bmp = mWoodObstacles.get(WOOD_OBSTACLES[bottomIndex]);
                }
                while (bmp == null) {
                    synchronized (mWoodObstacles) {
                        bmp = mWoodObstacles.get(WOOD_OBSTACLES[bottomIndex]);
                        if (bmp == null) {
                            try {
                                mWoodObstacles.wait();
                            } catch (InterruptedException e) {
                            }
                        }
                    }
                }
                if (bmp.getWidth() > width) {
                    width = bmp.getWidth();
                }
                bottom.setImageBitmap(bmp);
            } else {
                bottom.setVisibility(View.GONE);
            }
            int slots = (width / mSlotWidth) + 2;

            // If last obstacle had a top and this is a bottom or vice versa, insert a space
            if ((mLastObstacle & 0x1) > 0) {
                if ((currentObstacle & 0x2) > 0) {
                    addSpaceOrPresent(mSlotWidth);
                    i++;
                }
            } else if ((mLastObstacle & 0x2) > 0) {
                if ((currentObstacle & 0x1) > 0) {
                    addSpaceOrPresent(mSlotWidth);
                    i++;
                }
            }

            // If the new obstacle is too wide for the remaining space, skip it and fill spacer instead
            if ((i + slots) > totalSlots) {
                addSpaceOrPresent(mSlotWidth * (totalSlots - i));
                i = totalSlots;
            } else {
                mLastObstacle = currentObstacle;
                LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(slots * mSlotWidth,
                        LinearLayout.LayoutParams.WRAP_CONTENT);
                view.setLayoutParams(lp);
                mObstacleLayout.addView(view);
                i += slots;
            }
        } else {
            addSpaceOrPresent(mSlotWidth);
            i++;
        }
    }

    // Account for rounding errors in mSlotWidth
    int extra = ((screens * mScreenWidth) - (totalSlots * mSlotWidth));
    if (extra > 0) {
        // Add filler to ensure sync with background/foreground scrolls!
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(extra,
                LinearLayout.LayoutParams.MATCH_PARENT);
        View view = new View(this);
        mObstacleLayout.addView(view, lp);
    }
}

From source file:com.google.android.apps.santatracker.rocketsleigh.RocketSleighActivity.java

private void addCaveObstacles(int screens) {
    int totalSlots = screens * SLOTS_PER_SCREEN;
    for (int i = 0; i < totalSlots;) {
        // Any given "slot" has a 1 in 3 chance of having an obstacle
        if (mRandom.nextInt(2) == 0) {
            View view = mInflater.inflate(R.layout.obstacle_layout, null);
            ImageView top = (ImageView) view.findViewById(R.id.top_view);
            ImageView bottom = (ImageView) view.findViewById(R.id.bottom_view);
            ImageView back = (ImageView) view.findViewById(R.id.back_view);

            // Which obstacle?
            int width = 0;
            if ((mCaveObstacleIndex % 20) == 0) {
                ObstacleLoadTask task = new ObstacleLoadTask(getResources(), CAVE_OBSTACLES, mCaveObstacles,
                        mCaveObstacleList, mCaveObstacleIndex + 20, 2, mScaleX, mScaleY);
                task.execute();//from w ww. j  a v  a2s .c  om
            }
            int obstacle = mCaveObstacleList.get(mCaveObstacleIndex++);
            if (mCaveObstacleIndex >= mCaveObstacleList.size()) {
                mCaveObstacleIndex = 0;
            }
            //                int obstacle = mRandom.nextInt((CAVE_OBSTACLES.length/2));
            int topIndex = obstacle * 2;
            int bottomIndex = topIndex + 1;
            back.setVisibility(View.GONE);

            int currentObstacle = 0; // Same values as mLastObstacle
            if (CAVE_OBSTACLES[topIndex] != -1) {
                currentObstacle |= 1;
                Bitmap bmp = null;
                synchronized (mCaveObstacles) {
                    bmp = mCaveObstacles.get(CAVE_OBSTACLES[topIndex]);
                }
                while (bmp == null) {
                    synchronized (mCaveObstacles) {
                        bmp = mCaveObstacles.get(CAVE_OBSTACLES[topIndex]);
                        if (bmp == null) {
                            try {
                                mCaveObstacles.wait();
                            } catch (InterruptedException e) {
                            }
                        }
                    }
                }
                width = bmp.getWidth();
                top.setImageBitmap(bmp);
            } else {
                top.setVisibility(View.GONE);
            }

            if (CAVE_OBSTACLES[bottomIndex] != -1) {
                currentObstacle |= 2;
                Bitmap bmp = null;
                synchronized (mCaveObstacles) {
                    bmp = mCaveObstacles.get(CAVE_OBSTACLES[bottomIndex]);
                }
                while (bmp == null) {
                    synchronized (mCaveObstacles) {
                        bmp = mCaveObstacles.get(CAVE_OBSTACLES[bottomIndex]);
                        if (bmp == null) {
                            try {
                                mCaveObstacles.wait();
                            } catch (InterruptedException e) {
                            }
                        }
                    }
                }
                if (bmp.getWidth() > width) {
                    width = bmp.getWidth();
                }
                bottom.setImageBitmap(bmp);
                if (CAVE_OBSTACLES[bottomIndex] == R.drawable.img_mammoth) {
                    // Special case...
                    bottom.setTag(true);
                }
            } else {
                bottom.setVisibility(View.GONE);
            }
            int slots = (width / mSlotWidth);
            slots += 2;

            // If last obstacle had a top and this is a bottom or vice versa, insert a space
            if ((mLastObstacle & 0x1) > 0) {
                if ((currentObstacle & 0x2) > 0) {
                    addSpaceOrPresent(mSlotWidth);
                    i++;
                }
            } else if ((mLastObstacle & 0x2) > 0) {
                if ((currentObstacle & 0x1) > 0) {
                    addSpaceOrPresent(mSlotWidth);
                    i++;
                }
            }

            // If the new obstacle is too wide for the remaining space, skip it and fill spacer instead
            if ((i + slots) > totalSlots) {
                addSpaceOrPresent(mSlotWidth * (totalSlots - i));
                i = totalSlots;
            } else {
                mLastObstacle = currentObstacle;
                LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(slots * mSlotWidth,
                        LinearLayout.LayoutParams.WRAP_CONTENT);
                view.setLayoutParams(lp);
                mObstacleLayout.addView(view);
                i += slots;
            }
        } else {
            addSpaceOrPresent(mSlotWidth);
            i++;
        }
    }

    // Account for rounding errors in mSlotWidth
    int extra = ((screens * mScreenWidth) - (totalSlots * mSlotWidth));
    if (extra > 0) {
        // Add filler to ensure sync with background/foreground scrolls!
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(extra,
                LinearLayout.LayoutParams.MATCH_PARENT);
        View view = new View(this);
        mObstacleLayout.addView(view, lp);
    }
}

From source file:com.google.android.apps.santatracker.rocketsleigh.RocketSleighActivity.java

private void addFactoryObstacles(int screens) {
    int totalSlots = screens * SLOTS_PER_SCREEN;
    for (int i = 0; i < totalSlots;) {
        // Any given "slot" has a 1 in 3 chance of having an obstacle
        if (mRandom.nextInt(2) == 0) {
            View view = mInflater.inflate(R.layout.obstacle_layout, null);
            ImageView top = (ImageView) view.findViewById(R.id.top_view);
            ImageView bottom = (ImageView) view.findViewById(R.id.bottom_view);
            ImageView back = (ImageView) view.findViewById(R.id.back_view);

            // Which obstacle?
            int width = 0;
            //                int obstacle = mRandom.nextInt((FACTORY_OBSTACLES.length/2));
            if ((mFactoryObstacleIndex % 20) == 0) {
                ObstacleLoadTask task = new ObstacleLoadTask(getResources(), FACTORY_OBSTACLES,
                        mFactoryObstacles, mFactoryObstacleList, mFactoryObstacleIndex + 20, 2, mScaleX,
                        mScaleY);//from w  ww.  j  a  va 2  s . c  o  m
                task.execute();
            }
            int obstacle = mFactoryObstacleList.get(mFactoryObstacleIndex++);
            if (mFactoryObstacleIndex >= mFactoryObstacleList.size()) {
                mFactoryObstacleIndex = 0;
            }
            int topIndex = obstacle * 2;
            int bottomIndex = topIndex + 1;
            back.setVisibility(View.GONE);

            int currentObstacle = 0; // Same values as mLastObstacle
            if (FACTORY_OBSTACLES[topIndex] != -1) {
                currentObstacle |= 1;
                Bitmap bmp = null;
                synchronized (mFactoryObstacles) {
                    bmp = mFactoryObstacles.get(FACTORY_OBSTACLES[topIndex]);
                }
                while (bmp == null) {
                    synchronized (mFactoryObstacles) {
                        bmp = mFactoryObstacles.get(FACTORY_OBSTACLES[topIndex]);
                        if (bmp == null) {
                            try {
                                mFactoryObstacles.wait();
                            } catch (InterruptedException e) {
                            }
                        }
                    }
                }
                width = bmp.getWidth();
                top.setImageBitmap(bmp);
            } else {
                top.setVisibility(View.GONE);
            }

            if (FACTORY_OBSTACLES[bottomIndex] != -1) {
                currentObstacle |= 2;
                Bitmap bmp = null;
                synchronized (mFactoryObstacles) {
                    bmp = mFactoryObstacles.get(FACTORY_OBSTACLES[bottomIndex]);
                }
                while (bmp == null) {
                    synchronized (mFactoryObstacles) {
                        bmp = mFactoryObstacles.get(FACTORY_OBSTACLES[bottomIndex]);
                        if (bmp == null) {
                            try {
                                mFactoryObstacles.wait();
                            } catch (InterruptedException e) {
                            }
                        }
                    }
                }
                if (bmp.getWidth() > width) {
                    width = bmp.getWidth();
                }
                bottom.setImageBitmap(bmp);
            } else {
                bottom.setVisibility(View.GONE);
            }
            int slots = (width / mSlotWidth);
            if ((width % mSlotWidth) != 0) {
                slots++;
            }

            // If last obstacle had a top and this is a bottom or vice versa, insert a space
            if ((mLastObstacle & 0x1) > 0) {
                if ((currentObstacle & 0x2) > 0) {
                    addSpaceOrPresent(mSlotWidth);
                    i++;
                }
            } else if ((mLastObstacle & 0x2) > 0) {
                if ((currentObstacle & 0x1) > 0) {
                    addSpaceOrPresent(mSlotWidth);
                    i++;
                }
            }

            // If the new obstacle is too wide for the remaining space, skip it and fill spacer instead
            if ((i + slots) > totalSlots) {
                addSpaceOrPresent(mSlotWidth * (totalSlots - i));
                i = totalSlots;
            } else {
                mLastObstacle = currentObstacle;
                LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(slots * mSlotWidth,
                        LinearLayout.LayoutParams.WRAP_CONTENT);
                view.setLayoutParams(lp);
                mObstacleLayout.addView(view);
                i += slots;
            }
        } else {
            addSpaceOrPresent(mSlotWidth);
            i++;
        }
    }

    // Account for rounding errors in mSlotWidth
    int extra = ((screens * mScreenWidth) - (totalSlots * mSlotWidth));
    if (extra > 0) {
        // Add filler to ensure sync with background/foreground scrolls!
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(extra,
                LinearLayout.LayoutParams.MATCH_PARENT);
        View view = new View(this);
        view.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        mObstacleLayout.addView(view, lp);
    }
}

From source file:com.eleybourn.bookcatalogue.utils.Utils.java

/**
 * Shrinks the passed image file spec into the specificed dimensions, and returns the bitmap. If the view 
 * is non-null, the image is also placed in the view.
 * /*from  w  ww  .ja va 2 s .c  o  m*/
 * @param destView
 * @param filename
 * @param maxWidth
 * @param maxHeight
 * @param exact
 * 
 * @return
 */
private static Bitmap shrinkFileIntoImageView(ImageView destView, String filename, int maxWidth, int maxHeight,
        boolean exact) {
    Bitmap bm = null;

    // Read the file to get file size
    BitmapFactory.Options opt = new BitmapFactory.Options();
    opt.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(filename, opt);

    // If no size info, or a single pixel, assume file bad and set the 'alert' icon
    if (opt.outHeight <= 0 || opt.outWidth <= 0 || (opt.outHeight == 1 && opt.outWidth == 1)) {
        if (destView != null)
            destView.setImageResource(android.R.drawable.ic_dialog_alert);
        return null;
    }

    // Next time we don't just want the bounds, we want the file
    opt.inJustDecodeBounds = false;

    // Work out how to scale the file to fit in required bbox
    float widthRatio = (float) maxWidth / opt.outWidth;
    float heightRatio = (float) maxHeight / opt.outHeight;

    // Work out scale so that it fit exactly
    float ratio = widthRatio < heightRatio ? widthRatio : heightRatio;

    // Note that inSampleSize seems to ALWAYS be forced to a power of 2, no matter what we
    // specify, so we just work with powers of 2.
    int idealSampleSize = (int) android.util.FloatMath.ceil(1 / ratio); // This is the sample size we want to use
    // Get the nearest *bigger* power of 2.
    int samplePow2 = (int) Math.pow(2, Math.ceil(Math.log(idealSampleSize) / Math.log(2)));

    try {
        if (exact) {
            // Create one bigger than needed and scale it; this is an attempt to improve quality.
            opt.inSampleSize = samplePow2 / 2;
            if (opt.inSampleSize < 1)
                opt.inSampleSize = 1;
            Bitmap tmpBm = BitmapFactory.decodeFile(filename, opt);
            if (tmpBm == null) {
                // We ran out of memory, most likely
                // TODO: Need a way to try loading images after GC(), or something. Otherwise, covers in cover browser wil stay blank.
                Logger.logError(
                        new RuntimeException("Unexpectedly failed to decode bitmap; memory exhausted?"));
                return null;
            }
            android.graphics.Matrix matrix = new android.graphics.Matrix();
            // Fixup ratio based on new sample size and scale it.
            ratio = ratio / (1.0f / opt.inSampleSize);
            matrix.postScale(ratio, ratio);
            bm = Bitmap.createBitmap(tmpBm, 0, 0, opt.outWidth, opt.outHeight, matrix, true);
            // Recycle if original was not returned
            if (bm != tmpBm) {
                tmpBm.recycle();
                tmpBm = null;
            }
        } else {
            // Use a scale that will make image *no larger than* the desired size
            if (ratio < 1.0f)
                opt.inSampleSize = samplePow2;
            bm = BitmapFactory.decodeFile(filename, opt);
        }
    } catch (OutOfMemoryError e) {
        return null;
    }

    // Set ImageView and return bitmap
    if (destView != null)
        destView.setImageBitmap(bm);

    return bm;
}

From source file:self.philbrown.droidQuery.$.java

/**
 * Adds an Image over each selected View as a mask.
 * In most cases, this mask can be retrieved by querying siblings. For example:
 * <pre>/*from  w w  w . j  a v a2s  .  com*/
 * ImageView mask = (ImageView) $.with(myView).parent().selectChildren().selectImages().view(0);
 * </pre>
 * @param mask the bitmap to draw
 * @return this
 */
public $ mask(Bitmap mask) {
    for (View v : views) {
        ImageView image = new ImageView(context);
        image.setImageBitmap(mask);
        image.setScaleType(ScaleType.FIT_XY);
        ViewParent parent = v.getParent();
        if (parent != null && parent instanceof ViewGroup) {
            image.setLayoutParams(v.getLayoutParams());
            ((ViewGroup) parent).addView(image);
        } else if (v instanceof ViewGroup) {
            image.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT));
            ((ViewGroup) v).addView(image);
        }
    }
    return this;
}

From source file:self.philbrown.droidQuery.$.java

/**
 * Adds an Image over each selected View as a mask.
 * In most cases, this mask can be retrieved by querying siblings. For example:
 * <pre>/*from  w w  w.j  ava 2 s.c o m*/
 * ImageView mask = (ImageView) $.with(myView).parent().selectChildren().selectImages().view(0);
 * </pre>
 * @param source asset path, file path (starting with "file://") or URL to image
 * @param width specifies the output bitmap width
 * @param height specifies the output bitmap height
 * @param error if the given source is a file or asset, this receives a droidQuery wrapping the 
 * current context and the {@code Throwable} error. Otherwise, this will receive an
 * Ajax error.
 * @return this
 * @see AjaxOptions#error(Function)
 */
public $ mask(String source, int width, int height, Function error) {
    if (source.startsWith("file://")) {
        try {
            BitmapFactory.Options opt = new BitmapFactory.Options();
            opt.inPreferredConfig = Bitmap.Config.ARGB_8888;
            if (width >= 0)
                opt.outWidth = width;
            if (height >= 0)
                opt.outHeight = height;
            Bitmap bitmap = BitmapFactory.decodeFile(source.substring(6), opt);
            for (View v : views) {
                ImageView image = new ImageView(context);
                image.setImageBitmap(Bitmap.createBitmap(bitmap));
                image.setScaleType(ScaleType.FIT_XY);
                ViewParent parent = v.getParent();
                if (parent != null && parent instanceof ViewGroup) {
                    image.setLayoutParams(v.getLayoutParams());
                    ((ViewGroup) parent).addView(image);
                } else if (v instanceof ViewGroup) {
                    image.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                            ViewGroup.LayoutParams.MATCH_PARENT));
                    ((ViewGroup) v).addView(image);
                }
            }
        } catch (Throwable t) {
            if (error != null) {
                error.invoke($.with(context), t);
            }
        }
    } else if (URLUtil.isValidUrl(source)) {
        AjaxOptions options = new AjaxOptions().url(source).type("GET").dataType("image").context(context)
                .global(false).success(new Function() {
                    @Override
                    public void invoke($ droidQuery, Object... params) {
                        Bitmap bitmap = (Bitmap) params[0];
                        for (View v : views) {
                            ImageView image = new ImageView(context);
                            image.setImageBitmap(Bitmap.createBitmap(bitmap));
                            image.setScaleType(ScaleType.FIT_XY);
                            ViewParent parent = v.getParent();
                            if (parent != null && parent instanceof ViewGroup) {
                                image.setLayoutParams(v.getLayoutParams());
                                ((ViewGroup) parent).addView(image);
                            } else if (v instanceof ViewGroup) {
                                image.setLayoutParams(
                                        new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                                                ViewGroup.LayoutParams.MATCH_PARENT));
                                ((ViewGroup) v).addView(image);
                            }
                        }
                    }
                });

        if (error != null) {
            options.error(error);
        }
        if (width >= 0) {
            options.imageWidth(width);
        }
        if (height >= 0) {
            options.imageHeight(height);
        }
        $.ajax(options);
    } else {
        try {
            BitmapFactory.Options opt = new BitmapFactory.Options();
            opt.inSampleSize = 1;
            opt.inPurgeable = true;
            opt.inInputShareable = false;
            if (width >= 0)
                opt.outWidth = width;
            if (height >= 0)
                opt.outHeight = height;
            Bitmap bitmap = BitmapFactory.decodeStream(context.getAssets().open(source), new Rect(0, 0, 0, 0),
                    opt);
            for (View v : views) {
                ImageView image = new ImageView(context);
                image.setImageBitmap(Bitmap.createBitmap(bitmap));
                image.setScaleType(ScaleType.FIT_XY);
                ViewParent parent = v.getParent();
                if (parent != null && parent instanceof ViewGroup) {
                    image.setLayoutParams(v.getLayoutParams());
                    ((ViewGroup) parent).addView(image);
                } else if (v instanceof ViewGroup) {
                    image.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                            ViewGroup.LayoutParams.MATCH_PARENT));
                    ((ViewGroup) v).addView(image);
                }
            }

        } catch (Throwable t) {
            if (error != null) {
                error.invoke($.with(context), t);
            }
        }

    }
    return this;
}

From source file:com.andrewshu.android.reddit.threads.ThreadsListActivity.java

public static void fillThreadsListItemView(int position, View view, ThingInfo item, ListActivity activity,
        HttpClient client, RedditSettings settings,
        ThumbnailOnClickListenerFactory thumbnailOnClickListenerFactory) {

    Resources res = activity.getResources();

    TextView titleView = (TextView) view.findViewById(R.id.title);
    TextView votesView = (TextView) view.findViewById(R.id.votes);
    TextView numCommentsSubredditView = (TextView) view.findViewById(R.id.numCommentsSubreddit);
    TextView nsfwView = (TextView) view.findViewById(R.id.nsfw);
    //        TextView submissionTimeView = (TextView) view.findViewById(R.id.submissionTime);
    ImageView voteUpView = (ImageView) view.findViewById(R.id.vote_up_image);
    ImageView voteDownView = (ImageView) view.findViewById(R.id.vote_down_image);
    View thumbnailContainer = view.findViewById(R.id.thumbnail_view);
    FrameLayout thumbnailFrame = (FrameLayout) view.findViewById(R.id.thumbnail_frame);
    ImageView thumbnailImageView = (ImageView) view.findViewById(R.id.thumbnail);
    ProgressBar indeterminateProgressBar = (ProgressBar) view.findViewById(R.id.indeterminate_progress);

    // Set the title and domain using a SpannableStringBuilder
    SpannableStringBuilder builder = new SpannableStringBuilder();
    String title = item.getTitle();
    if (title == null)
        title = "";
    SpannableString titleSS = new SpannableString(title);
    int titleLen = title.length();
    titleSS.setSpan(//  ww  w.  j ava2 s .com
            new TextAppearanceSpan(activity,
                    Util.getTextAppearanceResource(settings.getTheme(), android.R.style.TextAppearance_Large)),
            0, titleLen, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

    String domain = item.getDomain();
    if (domain == null)
        domain = "";
    int domainLen = domain.length();
    SpannableString domainSS = new SpannableString("(" + item.getDomain() + ")");
    domainSS.setSpan(
            new TextAppearanceSpan(activity,
                    Util.getTextAppearanceResource(settings.getTheme(), android.R.style.TextAppearance_Small)),
            0, domainLen + 2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

    if (Util.isLightTheme(settings.getTheme())) {
        if (item.isClicked()) {
            ForegroundColorSpan fcs = new ForegroundColorSpan(res.getColor(R.color.purple));
            titleSS.setSpan(fcs, 0, titleLen, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        } else {
            ForegroundColorSpan fcs = new ForegroundColorSpan(res.getColor(R.color.blue));
            titleSS.setSpan(fcs, 0, titleLen, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        domainSS.setSpan(new ForegroundColorSpan(res.getColor(R.color.gray_50)), 0, domainLen + 2,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    } else {
        if (item.isClicked()) {
            ForegroundColorSpan fcs = new ForegroundColorSpan(res.getColor(R.color.gray_50));
            titleSS.setSpan(fcs, 0, titleLen, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        domainSS.setSpan(new ForegroundColorSpan(res.getColor(R.color.gray_75)), 0, domainLen + 2,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }

    builder.append(titleSS).append(" ").append(domainSS);
    titleView.setText(builder);

    votesView.setText("" + item.getScore());
    numCommentsSubredditView.setText(Util.showNumComments(item.getNum_comments()) + "  " + item.getSubreddit());

    if (item.isOver_18()) {
        nsfwView.setVisibility(View.VISIBLE);
    } else {
        nsfwView.setVisibility(View.GONE);
    }

    // Set the up and down arrow colors based on whether user likes
    if (settings.isLoggedIn()) {
        if (item.getLikes() == null) {
            voteUpView.setImageResource(R.drawable.vote_up_gray);
            voteDownView.setImageResource(R.drawable.vote_down_gray);
            votesView.setTextColor(res.getColor(R.color.gray_75));
        } else if (item.getLikes() == true) {
            voteUpView.setImageResource(R.drawable.vote_up_red);
            voteDownView.setImageResource(R.drawable.vote_down_gray);
            votesView.setTextColor(res.getColor(R.color.arrow_red));
        } else {
            voteUpView.setImageResource(R.drawable.vote_up_gray);
            voteDownView.setImageResource(R.drawable.vote_down_blue);
            votesView.setTextColor(res.getColor(R.color.arrow_blue));
        }
    } else {
        voteUpView.setImageResource(R.drawable.vote_up_gray);
        voteDownView.setImageResource(R.drawable.vote_down_gray);
        votesView.setTextColor(res.getColor(R.color.gray_75));
    }

    // Thumbnails open links
    if (thumbnailContainer != null) {
        if (Common.shouldLoadThumbnails(activity, settings)) {
            thumbnailContainer.setVisibility(View.VISIBLE);

            if (item.getUrl() != null) {
                OnClickListener thumbnailOnClickListener = thumbnailOnClickListenerFactory
                        .getThumbnailOnClickListener(item, activity);
                if (thumbnailOnClickListener != null) {
                    thumbnailFrame.setOnClickListener(thumbnailOnClickListener);
                }
            }

            // Show thumbnail based on ThingInfo
            if ("default".equals(item.getThumbnail()) || "self".equals(item.getThumbnail())
                    || StringUtils.isEmpty(item.getThumbnail())) {
                indeterminateProgressBar.setVisibility(View.GONE);
                thumbnailImageView.setVisibility(View.VISIBLE);
                thumbnailImageView.setImageResource(R.drawable.go_arrow);
            } else {
                indeterminateProgressBar.setVisibility(View.GONE);
                thumbnailImageView.setVisibility(View.VISIBLE);
                if (item.getThumbnailBitmap() != null) {
                    thumbnailImageView.setImageBitmap(item.getThumbnailBitmap());
                } else {
                    thumbnailImageView.setImageBitmap(null);
                    new ShowThumbnailsTask(activity, client, R.drawable.go_arrow)
                            .execute(new ThumbnailLoadAction(item, thumbnailImageView, position));
                }
            }

            // Set thumbnail background based on current theme
            if (Util.isLightTheme(settings.getTheme()))
                thumbnailFrame.setBackgroundResource(R.drawable.thumbnail_background_light);
            else
                thumbnailFrame.setBackgroundResource(R.drawable.thumbnail_background_dark);
        } else {
            // if thumbnails disabled, hide thumbnail icon
            thumbnailContainer.setVisibility(View.GONE);
        }
    }
}

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

public void showPreviews(final View anchor, int start, int end) {
    if (mWorkspace != null && mWorkspace.getChildCount() > 0) {
        if (newPreviews) {
            showingPreviews = true;/*from w  w w.ja  v a2  s . co  m*/
            hideDesktop(true);
            mWorkspace.lock();
            mWorkspace.openSense(true);
        } else {
            // check first if it's already open
            final PopupWindow window = (PopupWindow) anchor.getTag(R.id.TAG_PREVIEW);
            if (window != null)
                return;
            Resources resources = getResources();

            PersonaWorkspace personaWorkspace = mWorkspace;
            PersonaCellLayout cell = ((PersonaCellLayout) personaWorkspace.getChildAt(start));
            float max;
            ViewGroup preview;
            max = personaWorkspace.getChildCount();
            preview = new LinearLayout(this);

            Rect r = new Rect();
            // ADW: seems sometimes this throws an out of memory error....
            // so...
            try {
                resources.getDrawable(R.drawable.pr_preview_background).getPadding(r);
            } catch (OutOfMemoryError e) {
            }
            int extraW = (int) ((r.left + r.right) * max);
            int extraH = r.top + r.bottom;

            int aW = cell.getWidth() - extraW;
            float w = aW / max;

            int width = cell.getWidth();
            int height = cell.getHeight();
            // width -= (x + cell.getRightPadding());
            // height -= (y + cell.getBottomPadding());
            if (width != 0 && height != 0) {
                showingPreviews = true;
                float scale = w / width;

                int count = end - start;

                final float sWidth = width * scale;
                float sHeight = height * scale;

                PreviewTouchHandler handler = new PreviewTouchHandler(anchor);
                ArrayList<Bitmap> bitmaps = new ArrayList<Bitmap>(count);

                for (int i = start; i < end; i++) {
                    ImageView image = new ImageView(this);
                    cell = (PersonaCellLayout) personaWorkspace.getChildAt(i);
                    Bitmap bitmap = Bitmap.createBitmap((int) sWidth, (int) sHeight, Bitmap.Config.ARGB_8888);
                    cell.setDrawingCacheEnabled(false);
                    Canvas c = new Canvas(bitmap);
                    c.scale(scale, scale);
                    c.translate(-cell.getLeftPadding(), -cell.getTopPadding());
                    cell.dispatchDraw(c);

                    image.setBackgroundDrawable(resources.getDrawable(R.drawable.pr_preview_background));
                    image.setImageBitmap(bitmap);
                    image.setTag(i);
                    image.setOnClickListener(handler);
                    image.setOnFocusChangeListener(handler);
                    image.setFocusable(true);
                    if (i == mWorkspace.getCurrentScreen())
                        image.requestFocus();

                    preview.addView(image, LinearLayout.LayoutParams.WRAP_CONTENT,
                            LinearLayout.LayoutParams.WRAP_CONTENT);

                    bitmaps.add(bitmap);
                }

                PopupWindow p = new PopupWindow(this);
                p.setContentView(preview);
                p.setWidth((int) (sWidth * count + extraW));
                p.setHeight((int) (sHeight + extraH));
                p.setAnimationStyle(R.style.AnimationPreview);
                p.setOutsideTouchable(true);
                p.setFocusable(true);
                p.setBackgroundDrawable(new ColorDrawable(0));
                p.showAsDropDown(anchor, 0, 0);
                p.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    public void onDismiss() {
                        dismissPreview(anchor);
                    }
                });
                anchor.setTag(R.id.TAG_PREVIEW, p);
                anchor.setTag(R.id.workspace, preview);
                anchor.setTag(R.id.icon, bitmaps);
            }
        }
    }
}

From source file:eu.nubomedia.nubomedia_kurento_health_communicator_android.kc_and_communicator.util.FileUtils.java

public static void DownloadFromUrl(final String media, final String messageId, final Context ctx,
        final ImageView container, final Object object, final String timelineId, final String localId,
        final Long fileSize) {

    new AsyncTask<Void, Void, Boolean>() {
        private boolean retry = true;
        private Bitmap imageDownloaded;
        private BroadcastReceiver mDownloadCancelReceiver;
        private HttpGet job;
        private AccountManager am;
        private Account account;
        private String authToken;

        @Override/* w ww. j  ava 2  s .  c om*/
        protected void onPreExecute() {
            IntentFilter downloadFilter = new IntentFilter(ConstantKeys.BROADCAST_CANCEL_PROCESS);
            mDownloadCancelReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    String localIdToClose = (String) intent.getExtras().get(ConstantKeys.LOCALID);
                    if (localId.equals(localIdToClose)) {
                        try {
                            job.abort();
                        } catch (Exception e) {
                            log.debug("The process was canceled");
                        }
                        cancel(false);
                    }
                }
            };

            // registering our receiver
            ctx.getApplicationContext().registerReceiver(mDownloadCancelReceiver, downloadFilter);
        }

        @Override
        protected void onCancelled() {
            File file1 = new File(FileUtils.getDir(), localId + ConstantKeys.EXTENSION_JPG);
            File file2 = new File(FileUtils.getDir(), localId + ConstantKeys.EXTENSION_3GP);

            if (file1.exists()) {
                file1.delete();
            }
            if (file2.exists()) {
                file2.delete();
            }

            file1 = null;
            file2 = null;
            System.gc();
            try {
                ctx.getApplicationContext().unregisterReceiver(mDownloadCancelReceiver);
            } catch (Exception e) {
                log.debug("Receriver unregister from another code");
            }

            for (int i = 0; i < AppUtils.getlistOfDownload().size(); i++) {
                if (AppUtils.getlistOfDownload().get(i).equals(localId)) {
                    AppUtils.getlistOfDownload().remove(i);
                }
            }

            DataBasesAccess.getInstance(ctx.getApplicationContext()).MessagesDataBaseWriteTotal(localId, 100);

            Intent intent = new Intent();
            intent.setAction(ConstantKeys.BROADCAST_DIALOG_DOWNLOAD_FINISH);
            intent.putExtra(ConstantKeys.LOCALID, localId);
            ctx.sendBroadcast(intent);

            if (object != null) {
                ((ProgressDialog) object).dismiss();
            }
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            try {
                File file1 = new File(FileUtils.getDir(), localId + ConstantKeys.EXTENSION_JPG);
                File file2 = new File(FileUtils.getDir(), localId + ConstantKeys.EXTENSION_3GP);
                // firt we are goint to search the local files
                if ((!file1.exists()) && (!file2.exists())) {
                    account = AccountUtils.getAccount(ctx.getApplicationContext(), false);
                    am = (AccountManager) ctx.getSystemService(Context.ACCOUNT_SERVICE);
                    authToken = ConstantKeys.STRING_DEFAULT;
                    authToken = am.blockingGetAuthToken(account, ctx.getString(R.string.account_type), true);

                    MessagingClientService messageService = new MessagingClientService(
                            ctx.getApplicationContext());

                    URL urlObj = new URL(Preferences.getServerProtocol(ctx), Preferences.getServerAddress(ctx),
                            Preferences.getServerPort(ctx), ctx.getString(R.string.url_get_content));

                    String url = ConstantKeys.STRING_DEFAULT;
                    url = Uri.parse(urlObj.toString()).buildUpon().build().toString() + timelineId + "/"
                            + messageId + "/" + "content";

                    job = new HttpGet(url);
                    // first, get free space
                    FreeUpSpace(ctx, fileSize);
                    messageService.getContent(authToken, media, messageId, timelineId, localId, false, false,
                            fileSize, job);
                }

                if (file1.exists()) {
                    imageDownloaded = decodeSampledBitmapFromPath(file1.getAbsolutePath(), 200, 200);
                } else if (file2.exists()) {
                    imageDownloaded = ThumbnailUtils.createVideoThumbnail(file2.getAbsolutePath(),
                            MediaStore.Images.Thumbnails.MINI_KIND);
                }

                if (imageDownloaded == null) {
                    return false;
                }
                return true;
            } catch (Exception e) {
                deleteFiles();
                return false;
            }
        }

        @Override
        protected void onPostExecute(Boolean result) {
            // We have the media
            try {
                ctx.getApplicationContext().unregisterReceiver(mDownloadCancelReceiver);
            } catch (Exception e) {
                log.debug("Receiver was closed on cancel");
            }

            if (!(localId.contains(ConstantKeys.AVATAR))) {
                for (int i = 0; i < AppUtils.getlistOfDownload().size(); i++) {
                    if (AppUtils.getlistOfDownload().get(i).equals(localId)) {
                        AppUtils.getlistOfDownload().remove(i);
                    }
                }

                DataBasesAccess.getInstance(ctx.getApplicationContext()).MessagesDataBaseWriteTotal(localId,
                        100);

                Intent intent = new Intent();
                intent.setAction(ConstantKeys.BROADCAST_DIALOG_DOWNLOAD_FINISH);
                intent.putExtra(ConstantKeys.LOCALID, localId);
                ctx.sendBroadcast(intent);
            }

            if (object != null) {
                ((ProgressDialog) object).dismiss();
            }

            // Now the only container could be the avatar in edit screen
            if (container != null) {
                if (imageDownloaded != null) {
                    container.setImageBitmap(imageDownloaded);
                } else {
                    deleteFiles();
                    imageDownloaded = decodeSampledBitmapFromResource(ctx.getResources(),
                            R.drawable.ic_error_loading, 200, 200);
                    container.setImageBitmap(imageDownloaded);
                    Toast.makeText(ctx.getApplicationContext(),
                            ctx.getApplicationContext().getText(R.string.donwload_fail), Toast.LENGTH_SHORT)
                            .show();
                }
            } else {
                showMedia(localId, ctx, (ProgressDialog) object);
            }

        }

        private void deleteFiles() {
            File file1 = new File(FileUtils.getDir(), localId + ConstantKeys.EXTENSION_JPG);
            File file2 = new File(FileUtils.getDir(), localId + ConstantKeys.EXTENSION_3GP);
            if (file1.exists()) {
                file1.delete();
            }
            if (file2.exists()) {
                file2.delete();
            }
        }

    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}