Example usage for android.widget ImageView setImageResource

List of usage examples for android.widget ImageView setImageResource

Introduction

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

Prototype

@android.view.RemotableViewMethod(asyncImpl = "setImageResourceAsync")
public void setImageResource(@DrawableRes int resId) 

Source Link

Document

Sets a drawable as the content of this ImageView.

Usage

From source file:co.carlosjimenez.android.currencyalerts.app.MenuTint.java

private void colorOverflowMenuItem(ImageView overflow) {
    if (overflow != null) {
        if (overflowDrawableId != null) {
            overflow.setImageResource(overflowDrawableId);
        }/*from   w  w  w  . ja v a  2s . c o  m*/
        if (menuItemIconColor != null) {
            overflow.setColorFilter(menuItemIconColor);
        }
        if (menuItemIconAlpha != null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                overflow.setImageAlpha(menuItemIconAlpha);
            } else {
                overflow.setAlpha(menuItemIconAlpha);
            }
        }
    }
}

From source file:com.keylesspalace.tusky.AccountActivity.java

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_account);
    ButterKnife.bind(this);

    if (savedInstanceState != null) {
        accountId = savedInstanceState.getString("accountId");
    } else {/*from w  w w. j a  va 2  s .  com*/
        Intent intent = getIntent();
        accountId = intent.getStringExtra("id");
    }

    SharedPreferences preferences = getSharedPreferences(getString(R.string.preferences_file_key),
            Context.MODE_PRIVATE);
    String loggedInAccountId = preferences.getString("loggedInAccountId", null);

    final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    ActionBar actionBar = getSupportActionBar();

    if (actionBar != null) {
        actionBar.setTitle(null);
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setDisplayShowHomeEnabled(true);
    }

    // Add a listener to change the toolbar icon color when it enters/exits its collapsed state.
    AppBarLayout appBarLayout = (AppBarLayout) findViewById(R.id.account_app_bar_layout);
    final CollapsingToolbarLayout collapsingToolbar = (CollapsingToolbarLayout) findViewById(
            R.id.collapsing_toolbar);
    appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
        @AttrRes
        int priorAttribute = R.attr.account_toolbar_icon_tint_uncollapsed;

        @Override
        public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
            @AttrRes
            int attribute;
            if (collapsingToolbar.getHeight() + verticalOffset < 2
                    * ViewCompat.getMinimumHeight(collapsingToolbar)) {
                attribute = R.attr.account_toolbar_icon_tint_collapsed;
            } else {
                attribute = R.attr.account_toolbar_icon_tint_uncollapsed;
            }
            if (attribute != priorAttribute) {
                priorAttribute = attribute;
                Context context = toolbar.getContext();
                ThemeUtils.setDrawableTint(context, toolbar.getNavigationIcon(), attribute);
                ThemeUtils.setDrawableTint(context, toolbar.getOverflowIcon(), attribute);
            }
        }
    });

    FloatingActionButton floatingBtn = (FloatingActionButton) findViewById(R.id.floating_btn);
    floatingBtn.hide();

    CircularImageView avatar = (CircularImageView) findViewById(R.id.account_avatar);
    ImageView header = (ImageView) findViewById(R.id.account_header);
    avatar.setImageResource(R.drawable.avatar_default);
    header.setImageResource(R.drawable.account_header_default);

    obtainAccount();
    if (!accountId.equals(loggedInAccountId)) {
        isSelf = false;
        obtainRelationships();
    } else {
        /* Cause the options menu to update and instead show an options menu for when the
         * account being shown is their own account. */
        isSelf = true;
        invalidateOptionsMenu();
    }

    // Setup the tabs and timeline pager.
    AccountPagerAdapter adapter = new AccountPagerAdapter(getSupportFragmentManager(), this, accountId);
    String[] pageTitles = { getString(R.string.title_statuses), getString(R.string.title_follows),
            getString(R.string.title_followers) };
    adapter.setPageTitles(pageTitles);
    ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
    int pageMargin = getResources().getDimensionPixelSize(R.dimen.tab_page_margin);
    viewPager.setPageMargin(pageMargin);
    Drawable pageMarginDrawable = ThemeUtils.getDrawable(this, R.attr.tab_page_margin_drawable,
            R.drawable.tab_page_margin_dark);
    viewPager.setPageMarginDrawable(pageMarginDrawable);
    viewPager.setAdapter(adapter);
    tabLayout = (TabLayout) findViewById(R.id.tab_layout);
    tabLayout.setupWithViewPager(viewPager);
    for (int i = 0; i < tabLayout.getTabCount(); i++) {
        TabLayout.Tab tab = tabLayout.getTabAt(i);
        if (tab != null) {
            tab.setCustomView(adapter.getTabView(i, tabLayout));
        }
    }
}

From source file:com.cc.custom.uikit.PagerSlidingTabStrip.java

private void addIconTab(final int position, int resId) {

    ImageView tab = new ImageView(getContext());
    tab.setImageResource(resId);
    tab.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
    addTab(position, tab);//  w  w  w  .j  a v  a  2  s.  c o m

}

From source file:com.gsma.rcs.ri.messaging.adapter.TalkCursorAdapter.java

private void bindRcsFileTransferOutView(View view, Cursor cursor) {
    RcsFileTransferOutViewHolder holder = (RcsFileTransferOutViewHolder) view.getTag();
    holder.getTimestampText()//www  . j a v  a2  s .co m
            .setText(DateUtils.getRelativeTimeSpanString(cursor.getLong(holder.getColumnTimestampIdx()),
                    System.currentTimeMillis(), DateUtils.MINUTE_IN_MILLIS, DateUtils.FORMAT_ABBREV_RELATIVE));
    String mimeType = cursor.getString(holder.getColumnMimetypeIdx());
    StringBuilder sb = new StringBuilder(cursor.getString(holder.getColumnFilenameIdx()));
    long filesize = cursor.getLong(holder.getColumnFilesizeIdx());
    long transferred = cursor.getLong(holder.getColumnTransferredIdx());
    final ImageView imageView = holder.getFileImageView();
    imageView.setOnClickListener(null);
    imageView.setLayoutParams(mImageParamsDefault);
    imageView.setImageResource(R.drawable.ri_filetransfer_on);
    if (filesize != transferred) {
        holder.getProgressText()
                .setText(sb.append(" : ").append(Utils.getProgressLabel(transferred, filesize)).toString());
    } else {
        holder.getProgressText().setText(sb.append(" (")
                .append(FileUtils.humanReadableByteCount(filesize, true)).append(")").toString());
    }
    final Uri file = Uri.parse(cursor.getString(holder.getColumnContentIdx()));
    if (Utils.isImageType(mimeType)) {
        String filePath = FileUtils.getPath(mContext, file);
        Bitmap imageBitmap = null;
        if (filePath != null) {
            LruCache<String, BitmapCacheInfo> memoryCache = bitmapCache.getMemoryCache();
            BitmapCacheInfo bitmapCacheInfo = memoryCache.get(filePath);
            if (bitmapCacheInfo == null) {
                ImageBitmapLoader loader = new ImageBitmapLoader(mContext, memoryCache, MAX_IMAGE_WIDTH,
                        MAX_IMAGE_HEIGHT, new BitmapLoader.SetViewCallback() {
                            @Override
                            public void loadView(BitmapCacheInfo cacheInfo) {
                                imageView.setImageBitmap(cacheInfo.getBitmap());
                                imageView.setLayoutParams(mImageParams);
                            }
                        });
                loader.execute(filePath);
            } else {
                imageBitmap = bitmapCacheInfo.getBitmap();
            }
            if (imageBitmap != null) {
                imageView.setImageBitmap(imageBitmap);
                imageView.setLayoutParams(mImageParams);
            }
            imageView.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    Utils.showPicture(mActivity, file);
                }
            });
        }
    } else if (Utils.isAudioType(mimeType)) {
        imageView.setImageResource(R.drawable.headphone);
        imageView.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Utils.playAudio(mActivity, file);
            }
        });
    }
    holder.getStatusText().setText(getRcsFileTransferStatus(cursor, holder));
    boolean undeliveredExpiration = cursor.getInt(holder.getColumnExpiredDeliveryIdx()) == 1;
    holder.getStatusText().setCompoundDrawablesWithIntrinsicBounds(
            undeliveredExpiration ? R.drawable.chat_view_undelivered : 0, 0, 0, 0);
}

From source file:com.gsma.rcs.ri.messaging.adapter.TalkCursorAdapter.java

private void bindRcsFileTransferInView(View view, Cursor cursor) {
    final RcsFileTransferInViewHolder holder = (RcsFileTransferInViewHolder) view.getTag();
    holder.getTimestampText()/*from   ww  w.  java2 s.c om*/
            .setText(DateUtils.getRelativeTimeSpanString(cursor.getLong(holder.getColumnTimestampIdx()),
                    System.currentTimeMillis(), DateUtils.MINUTE_IN_MILLIS, DateUtils.FORMAT_ABBREV_RELATIVE));
    String mimeType = cursor.getString(holder.getColumnMimetypeIdx());
    StringBuilder sb = new StringBuilder(cursor.getString(holder.getColumnFilenameIdx()));
    long filesize = cursor.getLong(holder.getColumnFilesizeIdx());
    long transferred = cursor.getLong(holder.getColumnTransferredIdx());
    final ImageView imageView = holder.getFileImageView();
    imageView.setOnClickListener(null);
    imageView.setLayoutParams(mImageParamsDefault);
    imageView.setImageResource(R.drawable.ri_filetransfer_off);
    if (filesize != transferred) {
        holder.getProgressText()
                .setText(sb.append(" : ").append(Utils.getProgressLabel(transferred, filesize)).toString());
    } else {
        imageView.setImageResource(R.drawable.ri_filetransfer_on);
        final Uri file = Uri.parse(cursor.getString(holder.getColumnContentIdx()));
        final RcsService.ReadStatus readStatus = RcsService.ReadStatus
                .valueOf(cursor.getInt(holder.getColumnReadStatusIdx()));
        final String id = cursor.getString(cursor.getColumnIndexOrThrow(HistoryLog.ID));
        if (Utils.isImageType(mimeType)) {
            final String filePath = FileUtils.getPath(mContext, file);
            if (filePath != null) {
                LruCache<String, BitmapCacheInfo> memoryCache = bitmapCache.getMemoryCache();
                BitmapCacheInfo bitmapCacheInfo = memoryCache.get(filePath);
                if (bitmapCacheInfo == null) {
                    ImageBitmapLoader loader = new ImageBitmapLoader(mContext, memoryCache, MAX_IMAGE_WIDTH,
                            MAX_IMAGE_HEIGHT, new BitmapLoader.SetViewCallback() {
                                @Override
                                public void loadView(BitmapCacheInfo cacheInfo) {
                                    imageView.setImageBitmap(cacheInfo.getBitmap());
                                    imageView.setLayoutParams(mImageParams);
                                }
                            });
                    loader.execute(filePath);
                } else {
                    Bitmap imageBitmap = bitmapCacheInfo.getBitmap();
                    imageView.setImageBitmap(imageBitmap);
                    imageView.setLayoutParams(mImageParams);
                }
                imageView.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        Utils.showPicture(mActivity, file);
                        markFileTransferAsRead(id, readStatus);
                    }
                });
            }
        } else if (Utils.isAudioType(mimeType)) {
            imageView.setImageResource(R.drawable.headphone);
            imageView.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    Utils.playAudio(mActivity, file);
                    markFileTransferAsRead(id, readStatus);
                }
            });
        }
        holder.getProgressText().setText(sb.append(" (")
                .append(FileUtils.humanReadableByteCount(filesize, true)).append(")").toString());
    }
    holder.getStatusText().setText(getRcsFileTransferStatus(cursor, holder));
}

From source file:com.concentricsky.android.khanacademy.data.remote.KAAPIAdapter.java

/**
 * Call me from the UI thread, please./*from w w w  . j a  v a 2s  . c  o  m*/
 * 
 * Meant for use by broadcast receivers receiving ACTION_BADGE_EARNED.
 * */
public void toastBadge(Badge badge) {
    BadgeCategory category = badge.getCategory();
    //      Dao<BadgeCategory, Integer> dao = dataService.getHelper().getDao(BadgeCategory.class);
    //      dao.refresh(category);

    Toast toast = new Toast(dataService);
    View content = LayoutInflater.from(dataService).inflate(R.layout.badge, null, false);
    ImageView iconView = (ImageView) content.findViewById(R.id.badge_image);
    TextView pointsView = (TextView) content.findViewById(R.id.badge_points);
    TextView titleView = (TextView) content.findViewById(R.id.badge_title);
    TextView descView = (TextView) content.findViewById(R.id.badge_description);

    iconView.setImageResource(category.getIconResourceId());
    int points = badge.getPoints();
    if (points > 0) {
        pointsView.setText(points + "");
    } else {
        pointsView.setVisibility(View.GONE);
    }
    titleView.setText(badge.getDescription());
    descView.setText(badge.getSafe_extended_description());

    toast.setView(content);
    toast.setDuration(Toast.LENGTH_LONG);
    toast.setGravity(Gravity.TOP, 0, 200);
    toast.show();
}

From source file:com.facebook.android.friendsmash.RequestUserArrayAdapter.java

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    View listItemView = inflater.inflate(R.layout.request_list_item_view, parent, false);
    ProfilePictureView profilePicView = (ProfilePictureView) listItemView
            .findViewById(R.id.requestListItemProfilePic);
    TextView nameView = (TextView) listItemView.findViewById(R.id.requestListItemName);
    final ImageView checkBox = (ImageView) listItemView.findViewById(R.id.requestListItemCheckbox);

    JSONObject currentUser = users.get(position);

    profilePicView.setProfileId(currentUser.optString("id"));
    profilePicView.setCropped(true);// w  ww .  java 2s  . c  o m
    nameView.setText(currentUser.optString("first_name"));

    checkBox.setOnTouchListener(new View.OnTouchListener() {
        boolean checked = false;

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            // toggle image 
            if (checked) {
                checked = false;
                checkBox.setImageResource(R.drawable.checkbox_cold);
            } else {
                checked = true;
                checkBox.setImageResource(R.drawable.checkbox_hot);
            }
            return false;
        }
    });

    return listItemView;
}

From source file:com.example.view.astuetz.PagerSlidingTabStrip.java

@SuppressLint("NewApi")
private void addIconTab(int position, int resId, String notification) {
    FrameLayout tabItemCon = new FrameLayout(getContext());
    ImageView tab = new ImageView(getContext());
    tab.setImageResource(resId);
    tabItemCon.addView(tab);//from w  w  w  .  j a v a  2 s .c om
    tabIconlist.put(position, tab);
    ImageView notiSymbol = new ImageView(getContext());
    notiSymbol.setImageResource(R.drawable.badge_background);
    BadgeView noti = new BadgeView(getContext());
    noti.setText(notification);
    tabItemCon.addView(noti);
    tabItemCon.addView(notiSymbol);
    if (notification != null && !notification.equals("")) {
        noti.setVisibility(View.VISIBLE);
        notiSymbol.setVisibility(View.GONE);
    } else if (notification != null && notification.equals("")) {
        noti.setVisibility(View.GONE);
        notiSymbol.setVisibility(View.VISIBLE);
    } else {
        notiSymbol.setVisibility(View.GONE);
        noti.setVisibility(View.GONE);
    }
    int notiSySize = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20,
            getResources().getDisplayMetrics());
    noti.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
            Gravity.RIGHT | Gravity.TOP));
    notiSymbol.setLayoutParams(new LayoutParams(notiSySize, notiSySize, Gravity.RIGHT | Gravity.TOP));
    FrameLayout tabItem = new FrameLayout(getContext());
    tabItem.addView(tabItemCon);
    tabItemCon.setLayoutParams(
            new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.CENTER));
    addTab(position, tabItem);
}

From source file:com.nttec.everychan.cache.BitmapCache.java

/**
 *   ?  ?  ImageView.<br>/*from   ww  w. j  av  a2  s  . com*/
 * ? ImageView ??? ?:<ul>
 * <li>? ? ? ,  ?  (? ??,   )</li>
 * <li> {@link Boolean#TRUE},    ?</li>
 * <li> {@link Boolean#FALSE},      ( ?   downloadFromInternet == false)</li></ul>
 * @param hash ? ( ? )
 * @param url ? URL (?  ?)
 * @param maxSize ?   ??,     ,  0, ? ?? ?  ?
 * @param chan   ? ??   
 * @param zipFile - - ?  ? ?  (  null)
 * @param task ?? 
 * @param imageView  {@link ImageView},    
 * @param executor ? ?
 * @param handler Handler UI 
 * @param downloadFromInternet     
 * @param defaultResId ID ?? ?  , ?    ( ?  downloadFromInternet == false),
 *  0 - ?    
 */
public void asyncGet(String hash, String url, int maxSize, ChanModule chan, ReadableContainer zipFile,
        CancellableTask task, ImageView imageView, Executor executor, Handler handler,
        boolean downloadFromInternet, int defaultResId) {
    if (hash == null) {
        Logger.e(TAG, "received null hash for url: " + url);
        imageView.setTag(Boolean.FALSE);
        imageView.setImageResource(defaultResId);
        return;
    }
    Bitmap fromLru = getFromMemory(hash);
    if (fromLru != null) {
        imageView.setTag(Boolean.TRUE);
        imageView.setImageBitmap(fromLru);
        return;
    } else {
        imageView.setImageBitmap(EMPTY_BMP);
    }
    class ImageDownloader implements Runnable {
        private final String hash;
        private final String url;
        private final int maxSize;
        private final ChanModule chan;
        private final ReadableContainer zipFile;
        private final CancellableTask task;
        private final ImageView imageView;
        private final Handler handler;
        private final boolean downloadFromInternet;
        private final int defaultResId;

        public ImageDownloader(String hash, String url, int maxSize, ChanModule chan, ReadableContainer zipFile,
                CancellableTask task, ImageView imageView, Handler handler, boolean downloadFromInternet,
                int defaultResId) {
            this.hash = hash;
            this.url = url;
            this.maxSize = maxSize;
            this.chan = chan;
            this.zipFile = zipFile;
            this.task = task;
            this.imageView = imageView;
            this.handler = handler;
            this.downloadFromInternet = downloadFromInternet;
            this.defaultResId = defaultResId;
        }

        private Bitmap bmp;

        @Override
        public void run() {
            bmp = getFromCache(hash);
            if (bmp == null && zipFile != null)
                bmp = getFromContainer(hash, zipFile);
            if (bmp == null && downloadFromInternet) {
                bmp = download(hash, url, maxSize, chan, task);
            }
            if (task != null && task.isCancelled())
                return;
            if (imageView.getTag() == null || !imageView.getTag().equals(hash))
                return;
            if (bmp == null) {
                if (defaultResId == 0) {
                    imageView.setTag(Boolean.FALSE);
                    return;
                }
            }
            handler.post(new Runnable() {
                @Override
                public void run() {
                    try {
                        if (imageView.getTag() == null || !imageView.getTag().equals(hash))
                            return;
                        if (bmp != null) {
                            imageView.setTag(Boolean.TRUE);
                            imageView.setImageBitmap(bmp);
                        } else {
                            imageView.setTag(Boolean.FALSE);
                            imageView.setImageResource(defaultResId);
                        }
                    } catch (OutOfMemoryError oom) {
                        MainApplication.freeMemory();
                        Logger.e(TAG, oom);
                    }
                }
            });
        }
    }
    if (task != null && task.isCancelled())
        return;
    imageView.setTag(hash);
    executor.execute(new ImageDownloader(hash, url, maxSize, chan, zipFile, task, imageView, handler,
            downloadFromInternet, defaultResId));
}

From source file:com.odoo.OdooActivity.java

private void accountBoxToggle() {
    ImageView boxIndicator = (ImageView) findViewById(R.id.expand_account_box_indicator);
    boxIndicator.setImageResource(mAccountBoxExpanded ? R.drawable.ic_drawer_accounts_collapse
            : R.drawable.ic_drawer_accounts_expand);
    int hideTranslateY = -mDrawerAccountContainer.getHeight() / 4;
    if (mAccountBoxExpanded && mDrawerAccountContainer.getTranslationY() == 0) {
        // initial setup
        mDrawerAccountContainer.setAlpha(0);
        mDrawerAccountContainer.setTranslationY(hideTranslateY);
    }/*ww w .  j a  va2 s. co m*/

    AnimatorSet set = new AnimatorSet();
    set.addListener(new AnimatorListenerAdapter() {
        @Override
        public void onAnimationEnd(Animator animation) {
            mDrawerItemContainer.setVisibility(mAccountBoxExpanded ? View.INVISIBLE : View.VISIBLE);
            mDrawerAccountContainer.setVisibility(mAccountBoxExpanded ? View.VISIBLE : View.INVISIBLE);
        }

        @Override
        public void onAnimationCancel(Animator animation) {
            onAnimationEnd(animation);
        }
    });

    if (mAccountBoxExpanded) {
        mDrawerAccountContainer.setVisibility(View.VISIBLE);
        AnimatorSet subSet = new AnimatorSet();
        subSet.playTogether(
                ObjectAnimator.ofFloat(mDrawerAccountContainer, View.ALPHA, 1)
                        .setDuration(DRAWER_ACCOUNT_BOX_ANIMATION_DURATION),
                ObjectAnimator.ofFloat(mDrawerAccountContainer, View.TRANSLATION_Y, 0)
                        .setDuration(DRAWER_ACCOUNT_BOX_ANIMATION_DURATION));
        set.playSequentially(ObjectAnimator.ofFloat(mDrawerItemContainer, View.ALPHA, 0)
                .setDuration(DRAWER_ACCOUNT_BOX_ANIMATION_DURATION), subSet);
        set.start();
    } else {
        mDrawerItemContainer.setVisibility(View.VISIBLE);
        AnimatorSet subSet = new AnimatorSet();
        subSet.playTogether(
                ObjectAnimator.ofFloat(mDrawerAccountContainer, View.ALPHA, 0)
                        .setDuration(DRAWER_ACCOUNT_BOX_ANIMATION_DURATION),
                ObjectAnimator.ofFloat(mDrawerAccountContainer, View.TRANSLATION_Y, hideTranslateY)
                        .setDuration(DRAWER_ACCOUNT_BOX_ANIMATION_DURATION));
        set.playSequentially(subSet, ObjectAnimator.ofFloat(mDrawerItemContainer, View.ALPHA, 1)
                .setDuration(DRAWER_ACCOUNT_BOX_ANIMATION_DURATION));
        set.start();
    }

    set.start();

}