Example usage for android.widget ImageView setImageDrawable

List of usage examples for android.widget ImageView setImageDrawable

Introduction

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

Prototype

public void setImageDrawable(@Nullable Drawable drawable) 

Source Link

Document

Sets a drawable as the content of this ImageView.

Usage

From source file:com.filemanager.free.adapters.DrawerAdapter.java

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    if (values.get(position).isSection()) {
        ImageView view = new ImageView(context);
        if (m.theme1 == 0)
            view.setImageResource(R.color.divider);
        else/*from  w w w .j  a v  a  2  s  .c o  m*/
            view.setImageResource(R.color.divider_dark);
        view.setClickable(false);
        view.setFocusable(false);
        if (m.theme1 == 0)
            view.setBackgroundColor(Color.WHITE);
        else
            view.setBackgroundResource(R.color.background_material_dark);
        view.setLayoutParams(new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, m.dpToPx(17)));
        view.setPadding(0, m.dpToPx(8), 0, m.dpToPx(8));
        return view;
    } else {
        View view = inflater.inflate(R.layout.drawerrow, parent, false);
        final TextView txtTitle = (TextView) view.findViewById(R.id.firstline);
        final ImageView imageView = (ImageView) view.findViewById(R.id.icon);
        if (m.theme1 == 0) {
            view.setBackgroundResource(R.drawable.safr_ripple_white);
        } else {
            view.setBackgroundResource(R.drawable.safr_ripple_black);
        }
        view.setOnClickListener(new View.OnClickListener() {

            public void onClick(View p1) {
                m.selectItem(position);
            }
            // TODO: Implement this method

        });
        view.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if (!getItem(position).isSection())
                    // not to remove the first bookmark (storage) and permanent bookmarks
                    if (position > m.storage_count && position < values.size() - 7) {
                        EntryItem item = (EntryItem) getItem(position);
                        String path = (item).getPath();
                        if (DataUtils.containsBooks(new String[] { item.getTitle(), path }) != -1) {
                            m.renameBookmark((item).getTitle(), path);
                        } else if (path.startsWith("smb:/")) {
                            m.showSMBDialog(item.getTitle(), path, true);
                        }
                    } else if (position < m.storage_count) {
                        String path = ((EntryItem) getItem(position)).getPath();
                        if (!path.equals("/"))
                            new Futils().showProps(RootHelper.generateBaseFile(new File(path), true), m,
                                    m.theme1);
                    }

                // return true to denote no further processing
                return true;
            }
        });

        txtTitle.setText(((EntryItem) (values.get(position))).getTitle());
        imageView.setImageDrawable(getDrawable(position));
        imageView.clearColorFilter();
        if (myChecked.get(position)) {
            if (m.theme1 == 0)
                view.setBackgroundColor(Color.parseColor("#ffeeeeee"));
            else
                view.setBackgroundColor(Color.parseColor("#ff424242"));
            imageView.setColorFilter(fabskin);
            txtTitle.setTextColor(Color.parseColor(m.fabskin));
        } else {
            if (m.theme1 == 0) {
                imageView.setColorFilter(Color.parseColor("#666666"));
                txtTitle.setTextColor(ContextCompat.getColor(getContext(), android.R.color.black));
            } else {
                imageView.setColorFilter(Color.WHITE);
                txtTitle.setTextColor(ContextCompat.getColor(getContext(), android.R.color.white));
            }
        }

        return view;
    }
}

From source file:com.concavenp.artistrymuse.BaseAppCompatActivity.java

private BitmapImageViewTarget createBitmapImageViewTarget(final ImageView imageView) {

    return new BitmapImageViewTarget(imageView) {
        @Override/*from   w  w  w  .ja  v a 2 s  .  co  m*/
        protected void setResource(Bitmap bitmap) {

            int bitmapWidth = bitmap.getWidth();
            int bitmapHeight = bitmap.getHeight();
            int borderWidthHalf = 10;
            int bitmapSquareWidth = Math.min(bitmapWidth, bitmapHeight);
            int newBitmapSquare = bitmapSquareWidth + borderWidthHalf;

            Bitmap roundedBitmap = Bitmap.createBitmap(newBitmapSquare, newBitmapSquare,
                    Bitmap.Config.ARGB_8888);

            // Initialize a new Canvas to draw empty bitmap
            Canvas canvas = new Canvas(roundedBitmap);

            // Calculation to draw bitmap at the circular bitmap center position
            int x = borderWidthHalf + bitmapSquareWidth - bitmapWidth;
            int y = borderWidthHalf + bitmapSquareWidth - bitmapHeight;

            canvas.drawBitmap(bitmap, x, y, null);

            // Initializing a new Paint instance to draw circular border
            Paint borderPaint = new Paint();
            borderPaint.setStyle(Paint.Style.STROKE);
            borderPaint.setStrokeWidth(borderWidthHalf * 2);
            borderPaint.setColor(ResourcesCompat.getColor(getResources(), R.color.myApp_accent_700, null));

            canvas.drawCircle(canvas.getWidth() / 2, canvas.getWidth() / 2, newBitmapSquare / 2, borderPaint);

            RoundedBitmapDrawable circularBitmapDrawable = RoundedBitmapDrawableFactory.create(getResources(),
                    roundedBitmap);
            circularBitmapDrawable.setCircular(true);
            imageView.setImageDrawable(circularBitmapDrawable);

        }
    };
}

From source file:com.derrick.movies.MovieDetailsActivity.java

private void setTrailers(Videos videos) {
    videosList = videos.getResults();/* w ww . j  a  va 2 s.c  om*/
    int size = videosList.size();
    if (size == 1) {
        txt_title_trailer.setText("Trailer");
    }

    for (int i = 0; i < size; i++) {

        Result result = videosList.get(i);
        String url = IMAGE_YOUTUBE + result.getKey() + YOUTUBE_QUALITY;
        ImageView imageView;
        ImageView imageView_play;
        TextView txt_name;

        ViewGroup.LayoutParams lp = new RelativeLayout.LayoutParams(70, 70);
        ViewGroup.LayoutParams lp2 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT);

        RelativeLayout relativeLayout = new RelativeLayout(this);
        relativeLayout.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
                RelativeLayout.LayoutParams.MATCH_PARENT));

        if (size == 1) {
            imageView = new ImageView(getApplicationContext());
            imageView.setLayoutParams(new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT));
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);

        } else {
            imageView = new ImageView(getApplicationContext());
            imageView
                    .setLayoutParams(new RelativeLayout.LayoutParams(500, ViewGroup.LayoutParams.MATCH_PARENT));
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        }

        imageView_play = new ImageView(getApplicationContext());
        imageView_play.setLayoutParams(lp);
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) imageView_play
                .getLayoutParams();
        layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
        imageView_play.setLayoutParams(layoutParams);
        imageView_play.setScaleType(ImageView.ScaleType.CENTER_CROP);
        Drawable drawable = getResources()
                .getDrawable(getResources().getIdentifier("play", "drawable", getPackageName()));
        imageView_play.setImageDrawable(drawable);

        txt_name = new TextView(getApplicationContext());
        txt_name.setLayoutParams(lp2);
        RelativeLayout.LayoutParams layoutParams2 = (RelativeLayout.LayoutParams) txt_name.getLayoutParams();
        layoutParams2.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
        layoutParams2.setMargins(8, 8, 8, 16);
        txt_name.setLayoutParams(layoutParams2);
        txt_name.setTypeface(robotoCondensed);
        txt_name.setText(result.getName());
        txt_name.setTextColor(getResources().getColor(R.color.colorWhite));

        Glide.with(getBaseContext()).load(url).diskCacheStrategy(DiskCacheStrategy.ALL)
                .listener(new RequestListener<String, GlideDrawable>() {
                    @Override
                    public boolean onException(Exception e, String model, Target<GlideDrawable> target,
                            boolean isFirstResource) {
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(GlideDrawable resource, String model,
                            Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {

                        return false;
                    }
                }).into(imageView);

        // trailerSlider.addView(imageView_play);
        relativeLayout.addView(imageView);
        relativeLayout.addView(imageView_play);
        relativeLayout.addView(txt_name);
        trailerSlider.addView(relativeLayout);

    }

}

From source file:com.nd.pad.GreenBrowser.util.ImageDownloader.java

/**
 * Same as download but the image is always downloaded and the cache is not used. Kept private at the moment as its
 * interest is not clear./*  ww  w .  j  a  v a 2s. co  m*/
 */
private void forceDownload(String url, ImageView imageView, int width, int height, String parentFullFileName,
        int loadingDrawable_ID, int failDrawable_ID, boolean isSaveLocal, ImageDownLoaderAction action) {
    // State sanity: url is guaranteed to never be null in
    // DownloadedDrawable and cache keys.
    if (url == null) {
        imageView.setImageResource(failDrawable_ID);
        return;
    }
    if (cancelPotentialDownload(url, imageView)) {
        /*modeCORRECT*/
        switch (mode) {
        case NO_ASYNC_TASK:
            Bitmap bitmap = downloadBitmap(url);
            addBitmapToCache(url, bitmap);
            imageView.setImageBitmap(bitmap);
            break;

        case NO_DOWNLOADED_DRAWABLE:
            imageView.setMinimumHeight(156);
            BitmapDownloaderTask task = new BitmapDownloaderTask(imageView, failDrawable_ID, isSaveLocal,
                    action);
            task.execute(url);
            break;

        case CORRECT:
            task = new BitmapDownloaderTask(imageView, width, height, parentFullFileName, failDrawable_ID,
                    isSaveLocal, action);
            DownloadedDrawable downloadedDrawable = new DownloadedDrawable(task, loadingDrawable_ID);
            imageView.setImageDrawable(downloadedDrawable);
            imageView.setMinimumHeight(156);
            try {
                task.execute(url);
            } catch (RejectedExecutionException localRejectedExecutionException) {
            }
            break;
        }
    }
}

From source file:com.android.contacts.list.MultiSelectContactsListFragment.java

/**
 * Show account icon, count of contacts and account name in the header of the list.
 */// w w w.ja v  a  2s .  c o  m
protected void bindListHeader(Context context, View listView, View accountFilterContainer,
        AccountWithDataSet accountWithDataSet, int memberCount) {
    if (memberCount < 0) {
        hideHeaderAndAddPadding(context, listView, accountFilterContainer);
        return;
    }

    bindListHeaderCommon(listView, accountFilterContainer);

    final AccountTypeManager accountTypeManager = AccountTypeManager.getInstance(context);
    final AccountType accountType = accountTypeManager.getAccountType(accountWithDataSet.type,
            accountWithDataSet.dataSet);

    // Set text of count of contacts and account name
    final TextView accountFilterHeader = (TextView) accountFilterContainer
            .findViewById(R.id.account_filter_header);
    final String headerText = shouldShowAccountName(accountType)
            ? String.format(context.getResources().getQuantityString(R.plurals.contacts_count_with_account,
                    memberCount), memberCount, accountWithDataSet.name)
            : context.getResources().getQuantityString(R.plurals.contacts_count, memberCount, memberCount);
    accountFilterHeader.setText(headerText);
    accountFilterHeader.setAllCaps(false);

    // Set icon of the account
    final Drawable icon = accountType != null ? accountType.getDisplayIcon(context) : null;
    final ImageView accountFilterHeaderIcon = (ImageView) accountFilterContainer
            .findViewById(R.id.account_filter_icon);

    // If it's a writable Google account, we set icon size as 24dp; otherwise, we set it as
    // 20dp. And we need to change margin accordingly. This is because the Google icon looks
    // smaller when the icons are of the same size.
    if (accountType instanceof GoogleAccountType) {
        accountFilterHeaderIcon.getLayoutParams().height = getResources()
                .getDimensionPixelOffset(R.dimen.contact_browser_list_header_icon_size);
        accountFilterHeaderIcon.getLayoutParams().width = getResources()
                .getDimensionPixelOffset(R.dimen.contact_browser_list_header_icon_size);

        setMargins(accountFilterHeaderIcon,
                getResources().getDimensionPixelOffset(R.dimen.contact_browser_list_header_icon_left_margin),
                getResources().getDimensionPixelOffset(R.dimen.contact_browser_list_header_icon_right_margin));
    } else {
        accountFilterHeaderIcon.getLayoutParams().height = getResources()
                .getDimensionPixelOffset(R.dimen.contact_browser_list_header_icon_size_alt);
        accountFilterHeaderIcon.getLayoutParams().width = getResources()
                .getDimensionPixelOffset(R.dimen.contact_browser_list_header_icon_size_alt);

        setMargins(accountFilterHeaderIcon,
                getResources()
                        .getDimensionPixelOffset(R.dimen.contact_browser_list_header_icon_left_margin_alt),
                getResources()
                        .getDimensionPixelOffset(R.dimen.contact_browser_list_header_icon_right_margin_alt));
    }
    accountFilterHeaderIcon.requestLayout();

    accountFilterHeaderIcon.setVisibility(View.VISIBLE);
    accountFilterHeaderIcon.setImageDrawable(icon);
}

From source file:com.nd.teacherplatform.util.ImageDownloader.java

/**
 * Same as download but the image is always downloaded and the cache is not
 * used. Kept private at the moment as its interest is not clear.
 *//*from  ww  w.j a va  2 s.  c o  m*/
private void forceDownload(String url, ImageView imageView, int width, int height, String parentFullFileName,
        int loadingDrawable_ID, int failDrawable_ID, boolean isSaveLocal, ImageDownLoaderAction action) {
    // State sanity: url is guaranteed to never be null in
    // DownloadedDrawable and cache keys.
    if (url == null) {
        imageView.setImageResource(failDrawable_ID);
        return;
    }
    if (cancelPotentialDownload(url, imageView)) {
        /* modeCORRECT */
        switch (mode) {
        case NO_ASYNC_TASK:
            Bitmap bitmap = downloadBitmap(url);
            addBitmapToCache(url, bitmap);
            imageView.setImageBitmap(bitmap);
            break;

        case NO_DOWNLOADED_DRAWABLE:
            imageView.setMinimumHeight(156);
            BitmapDownloaderTask task = new BitmapDownloaderTask(imageView, failDrawable_ID, isSaveLocal,
                    action);
            task.execute(url);
            break;

        case CORRECT:
            task = new BitmapDownloaderTask(imageView, width, height, parentFullFileName, failDrawable_ID,
                    isSaveLocal, action);
            DownloadedDrawable downloadedDrawable = new DownloadedDrawable(task, loadingDrawable_ID);
            imageView.setImageDrawable(downloadedDrawable);
            imageView.setMinimumHeight(156);
            try {
                task.execute(url);
            } catch (RejectedExecutionException localRejectedExecutionException) {
            }
            break;
        }
    }
}

From source file:io.intue.kamu.BestNearbyFragment.java

@Override
public void bindCollectionItemView(Context context, View view, int groupId, int indexInGroup, int dataIndex,
        Object tag) {/*w  w  w . jav a 2 s  .  c om*/
    //        if (mCursor == null || !mCursor.moveToPosition(dataIndex)) {
    //            LOGW(TAG, "Can't bind collection view item, dataIndex=" + dataIndex +
    //                    (mCursor == null ? ": cursor is null" : ": bad data index."));
    //            return;
    //        }

    if (mresult == null) {
        return;
    }
    Venue result = mresult.get(dataIndex);

    final String sessionId = result.getId();
    if (sessionId == null) {
        return;
    }

    // first, read session info from cursor and put it in convenience variables
    final String sessionTitle = result.getName();
    //final String speakerNames = "SessionsQuery.SPEAKER_NAMES";
    //final String sessionAbstract = "SessionsQuery.ABSTRACT";
    //final long sessionStart = 44454544;
    //final long sessionEnd = 334343433;
    //final String roomName = "SessionsQuery.ROOM_NAME";
    int sessionColor = 0;
    sessionColor = sessionColor == 0 ? getResources().getColor(R.color.transparent) : sessionColor;
    //final String snippet = "SessionsQuery.SNIPPET";
    final Spannable styledSnippet = null;
    final boolean starred = false;
    //final String[] tags = "A,B,C".split(",");

    // now let's compute a few pieces of information from the data, which we will use
    // later to decide what to render where
    final boolean hasLivestream = false;
    final long now = UIUtils.getCurrentTime(context);
    final boolean happeningNow = false;

    // text that says "LIVE" if session is live, or empty if session is not live
    //final String liveNowText =  "";

    // get reference to all the views in the layout we will need
    final TextView titleView = (TextView) view.findViewById(R.id.session_title);
    final TextView subtitleView = (TextView) view.findViewById(R.id.session_subtitle);
    final TextView shortSubtitleView = (TextView) view.findViewById(R.id.session_subtitle_short);
    final TextView snippetView = (TextView) view.findViewById(R.id.session_snippet);
    //final TextView abstractView = (TextView) view.findViewById(R.id.session_abstract);
    //final TextView categoryView = (TextView) view.findViewById(R.id.session_category);
    final View boxView = view.findViewById(R.id.info_box);
    final View sessionTargetView = view.findViewById(R.id.session_target);

    if (sessionColor == 0) {
        // use default
        sessionColor = getResources().getColor(R.color.transparent);
    }
    sessionColor = UIUtils.scaleSessionColorToDefaultBG(sessionColor);

    ImageView photoView = (ImageView) view.findViewById(R.id.session_photo_colored);
    if (photoView != null) {
        if (!mPreloader.isDimensSet()) {
            final ImageView finalPhotoView = photoView;
            photoView.post(new Runnable() {
                @Override
                public void run() {
                    mPreloader.setDimens(finalPhotoView.getWidth(), finalPhotoView.getHeight());
                }
            });
        }
        // colored
        photoView.setColorFilter(UIUtils.setColorAlpha(sessionColor, UIUtils.SESSION_PHOTO_SCRIM_ALPHA));
    } else {
        photoView = (ImageView) view.findViewById(R.id.session_photo);
    }
    ((BaseActivity) getActivity()).getLPreviewUtils().setViewName(photoView, "photo_" + sessionId);

    // when we load a photo, it will fade in from transparent so the
    // background of the container must be the session color to avoid a white flash
    ViewParent parent = photoView.getParent();
    if (parent != null && parent instanceof View) {
        ((View) parent).setBackgroundColor(sessionColor);
    } else {
        photoView.setBackgroundColor(sessionColor);
    }

    String photo = result.getPhotoUrl();
    if (!TextUtils.isEmpty(photo)) {
        mImageLoader.loadImage(photo, photoView, true /*crop*/);
    } else {
        // cleaning the (potentially) recycled photoView, in case this session has no photo:
        photoView.setImageDrawable(null);
    }

    // render title
    titleView.setText(sessionTitle == null ? "?" : sessionTitle);

    // render subtitle into either the subtitle view, or the short subtitle view, as available
    if (subtitleView != null) {
        subtitleView.setText(result.getAddress());
    } else if (shortSubtitleView != null) {
        shortSubtitleView.setText(result.getAddress());
    }

    // render category
    //        if (categoryView != null) {
    //            TagMetadata.Tag groupTag = mTagMetadata.getSessionGroupTag(tags);
    //            if (groupTag != null && !Config.Tags.SESSIONS.equals(groupTag.getId())) {
    //                categoryView.setText(groupTag.getName());
    //                categoryView.setVisibility(View.VISIBLE);
    //            } else {
    //                categoryView.setVisibility(View.GONE);
    //            }
    //        }

    // if a snippet view is available, render the session snippet there.
    if (snippetView != null) {
        //if (mIsSearchCursor) {
        // render the search snippet into the snippet view
        snippetView.setText(styledSnippet);
        //            } else {
        //                // render speaker names and abstracts into the snippet view
        //                mBuffer.setLength(0);
        //                if (!TextUtils.isEmpty(speakerNames)) {
        //                    mBuffer.append(speakerNames).append(". ");
        //                }
        //                if (!TextUtils.isEmpty(sessionAbstract)) {
        //                    mBuffer.append(sessionAbstract);
        //                }
        //                snippetView.setText(mBuffer.toString());
        //            }
    }

    //        if (abstractView != null && !mIsSearchCursor) {
    //            // render speaker names and abstracts into the abstract view
    //            mBuffer.setLength(0);
    //            if (!TextUtils.isEmpty(speakerNames)) {
    //                mBuffer.append(speakerNames).append("\n\n");
    //            }
    //            if (!TextUtils.isEmpty(sessionAbstract)) {
    //                mBuffer.append(sessionAbstract);
    //            }
    //            abstractView.setText(mBuffer.toString());
    //        }

    // in expanded mode, the box background color follows the session color
    //if (useExpandedMode()) {
    boxView.setBackgroundColor(sessionColor);
    //}

    // show or hide the "in my schedule" indicator
    view.findViewById(R.id.indicator_in_schedule).setVisibility(starred ? View.VISIBLE : View.INVISIBLE);

    // if we are in condensed mode and this card is the hero card (big card at the top
    // of the screen), set up the message card if necessary.
    if (groupId == HERO_GROUP_ID) {
        // this is the hero view, so we might want to show a message card
        final boolean cardShown = setupMessageCard(view);

        // if this is the wide hero layout, show or hide the card or the session abstract
        // view, as appropriate (they are mutually exclusive).
        final View cardContainer = view.findViewById(R.id.message_card_container_wide);
        final View abstractContainer = view.findViewById(R.id.session_abstract);
        if (cardContainer != null && abstractContainer != null) {
            cardContainer.setVisibility(cardShown ? View.VISIBLE : View.GONE);
            abstractContainer.setVisibility(cardShown ? View.GONE : View.VISIBLE);
            abstractContainer.setBackgroundColor(sessionColor);
        }
    }

    // if this session is live right now, display the "LIVE NOW" icon on top of it
    View liveNowBadge = view.findViewById(R.id.live_now_badge);
    if (liveNowBadge != null) {
        liveNowBadge.setVisibility(happeningNow && hasLivestream ? View.VISIBLE : View.GONE);
    }

    // if this view is clicked, open the session details view
    final View finalPhotoView = photoView;
    sessionTargetView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mCallbacks.onSessionSelected(sessionId, finalPhotoView);
        }
    });

    // animate this card
    //        if (dataIndex > mMaxDataIndexAnimated) {
    //            mMaxDataIndexAnimated = dataIndex;
    //        }
}

From source file:com.hybris.mobile.app.commerce.adapter.VariantAdapter.java

/**
 * Create the view for spinner item/*from ww w .j  ava 2s  .  c  o  m*/
 *
 * @param position
 * @param convertView
 * @param parent
 * @return
 */
public View getCustomView(int position, View convertView, ViewGroup parent) {

    View rowView;

    if (convertView == null) {
        LayoutInflater inflater = (LayoutInflater) getContext()
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        rowView = inflater.inflate(R.layout.item_product_variant, parent, false);
    } else {
        rowView = convertView;
    }

    VariantOption productVariant = getItem(position);

    TextView productVariantName = (TextView) rowView.findViewById(R.id.product_variant_name);
    final ImageView productVariantImage = (ImageView) rowView.findViewById(R.id.product_variant_image);
    final ProgressBar productVariantProgressBar = (ProgressBar) rowView
            .findViewById(R.id.product_variant_image_loading);

    productVariantName.setText(
            ((List<VariantOptionQualifier>) productVariant.getVariantOptionQualifiers()).get(0).getValue());

    if (((List<VariantOptionQualifier>) productVariant.getVariantOptionQualifiers()).get(0)
            .getImage() != null) { // Loading the product image
        if (CommerceApplication.isOnline()) {

            if (StringUtils
                    .isNotBlank(((List<VariantOptionQualifier>) productVariant.getVariantOptionQualifiers())
                            .get(0).getImage().getUrl())) {

                CommerceApplication.getContentServiceHelper().loadImage(
                        ((List<VariantOptionQualifier>) productVariant.getVariantOptionQualifiers()).get(0)
                                .getImage().getUrl(),
                        null, productVariantImage, 0, 0, true, new OnRequestListener() {

                            @Override
                            public void beforeRequest() {
                                productVariantImage.setImageResource(android.R.color.transparent);
                                productVariantImage.setVisibility(View.GONE);
                                productVariantProgressBar.setVisibility(View.VISIBLE);
                            }

                            @Override
                            public void afterRequestBeforeResponse() {

                            }

                            @Override
                            public void afterRequest(boolean isDataSynced) {
                                productVariantImage.setVisibility(View.VISIBLE);
                                productVariantProgressBar.setVisibility(View.GONE);
                            }
                        }, true);
            }

        } else {
            Log.i(TAG, "Application offline, displaying no image for variant " + productVariant.getCode());
            productVariantImage
                    .setImageDrawable(getContext().getResources().getDrawable(R.drawable.no_image_product));
            productVariantImage.setVisibility(View.VISIBLE);
        }

    }

    return rowView;
}

From source file:com.aapbd.utils.image.CacheImageDownloader.java

private void scaleImage1(ImageView view) {
    // Get the ImageView and its bitmap

    final Drawable drawing = view.getDrawable();
    if (drawing == null) {
        return; // Checking for null & return, as suggested in comments
    }/*from   ww w  .  j a va2 s . c  o  m*/
    final Bitmap bitmap = ((BitmapDrawable) drawing).getBitmap();

    // Get current dimensions AND the desired bounding box
    int width = bitmap.getWidth();
    int height = bitmap.getHeight();
    final int bounding = dpToPx(view.getContext(), 300);
    Log.i("Test", "original width = " + Integer.toString(width));
    Log.i("Test", "original height = " + Integer.toString(height));
    Log.i("Test", "bounding = " + Integer.toString(bounding));

    // Determine how much to scale: the dimension requiring less scaling is
    // closer to the its side. This way the image always stays inside your
    // bounding box AND either x/y axis touches it.
    final float xScale = ((float) bounding) / width;
    final float yScale = ((float) bounding) / height;
    final float scale = (xScale <= yScale) ? xScale : yScale;
    Log.i("Test", "xScale = " + Float.toString(xScale));
    Log.i("Test", "yScale = " + Float.toString(yScale));
    Log.i("Test", "scale = " + Float.toString(scale));

    // Create a matrix for the scaling and add the scaling data
    final Matrix matrix = new Matrix();
    matrix.postScale(scale, scale);

    // Create a new bitmap and convert it to a format understood by the
    // ImageView
    final Bitmap scaledBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
    width = scaledBitmap.getWidth(); // re-use
    height = scaledBitmap.getHeight(); // re-use
    final BitmapDrawable result = new BitmapDrawable(scaledBitmap);
    Log.i("Test", "scaled width = " + Integer.toString(width));
    Log.i("Test", "scaled height = " + Integer.toString(height));

    // Apply the scaled bitmap
    view.setImageDrawable(result);

    // Now change ImageView's dimensions to match the scaled image
    final LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams();
    params.width = width;
    params.height = height;
    view.setLayoutParams(params);

    Log.i("Test", "done");
}

From source file:com.andrada.sitracker.ui.fragment.PublicationInfoFragment.java

private void setOrAnimateReadPubIcon(final ImageView imageView, PublicationState currentState,
        boolean allowAnimate) {
    final int imageResId = currentState.equals(PublicationState.READY_FOR_READING)
            ? R.drawable.read_pub_button_icon_checked
            : currentState.equals(PublicationState.DOWNLOADING) ? R.drawable.download_pub_icon_fab_up
                    : R.drawable.read_pub_button_icon_unchecked;

    if (imageView.getTag() != null) {
        if (imageView.getTag() instanceof Animator) {
            Animator anim = (Animator) imageView.getTag();
            anim.end();/*from  ww w .ja v  a  2 s .  c  o m*/
            ViewHelper.setAlpha(imageView, 1f);
        }
    }
    /*
    if (imageView.getBackground() instanceof AnimationDrawable) {
    AnimationDrawable frameAnimation = (AnimationDrawable) imageView.getBackground();
    frameAnimation.stop();
    imageView.setBackgroundResource(0);
    }*/

    if (allowAnimate && currentState.equals(PublicationState.DOWNLOADING)) {
        int duration = getResources().getInteger(android.R.integer.config_shortAnimTime);
        Animator outAnimator = ObjectAnimator.ofFloat(imageView, "alpha", 0f);
        outAnimator.setDuration(duration);
        outAnimator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                imageView.setImageDrawable(null);
                imageView.setBackgroundResource(imageResId);
                Drawable frameAnimation = imageView.getBackground();
                if (frameAnimation instanceof AnimationDrawable) {
                    ((AnimationDrawable) frameAnimation).start();
                }
            }
        });

        ObjectAnimator inAnimator = ObjectAnimator.ofFloat(imageView, "alpha", 1f);
        inAnimator.setDuration(duration * 2);
        final AnimatorSet set = new AnimatorSet();
        set.playSequentially(outAnimator, inAnimator);
        set.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                imageView.setTag(null);
            }
        });
        imageView.setTag(set);
        set.start();

    } else if (allowAnimate && currentState.equals(PublicationState.READY_FOR_READING)) {
        int duration = getResources().getInteger(android.R.integer.config_shortAnimTime);
        Animator outAnimator = ObjectAnimator.ofFloat(imageView, "alpha", 0f);
        outAnimator.setDuration(duration);
        outAnimator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                imageView.setBackgroundResource(0);
                imageView.setImageResource(imageResId);
            }
        });
        ObjectAnimator inAnimator = ObjectAnimator.ofFloat(imageView, "alpha", 1f);
        inAnimator.setDuration(duration * 2);
        final AnimatorSet set = new AnimatorSet();
        set.playSequentially(outAnimator, inAnimator);
        set.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                imageView.setTag(null);
            }
        });
        imageView.setTag(set);
        set.start();
    } else if (!allowAnimate && currentState.equals(PublicationState.DOWNLOADING)) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                imageView.setImageDrawable(null);
                imageView.setBackgroundResource(imageResId);
                AnimationDrawable frameAnimation = (AnimationDrawable) imageView.getBackground();
                frameAnimation.start();
            }
        });
    } else {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                imageView.setBackgroundResource(0);
                imageView.setImageResource(imageResId);
            }
        });
    }
}