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.itsherpa.andg.imageloader.ImageWorker.java

/**
 * Load an image specified by the data parameter into an ImageView (override
 * {@link ImageWorker#processBitmap(Object)} to define the processing
 * logic). A memory and disk cache will be used if an {@link ImageCache} has
 * been added using//  w w w  .j  a va2s. c  o  m
 * {@link ImageWorker#addImageCache(FragmentManager, ImageCache.ImageCacheParams)}
 * . If the image is found in the memory cache, it is set immediately,
 * otherwise an {@link AsyncTask} will be created to asynchronously load the
 * bitmap.
 * 
 * @param data
 *            The URL of the image to download.
 * @param imageView
 *            The ImageView to bind the downloaded image to.
 */
private void loadImage(Object data, ImageView imageView, int width, int height, int gender, boolean hasCover,
        ImageListener imageListener) {

    if (data == null) {
        return;
    }
    BitmapDrawable value = null;
    if (mImageCache != null) {
        value = mImageCache.getBitmapFromMemCache(getCacheKeyFromObject(data));
    }
    boolean isCircle = false;
    if (data instanceof CircleImageRequest) {
        isCircle = true;
    }
    Bitmap loadingBitmap = getBitmapCover(hasCover, gender, isCircle);

    if (value != null) {
        // Bitmap found in memory cache
        Bitmap bitmap = value.getBitmap();
        if (isCircle) {
            bitmap = Utils.getBitmapInCircle(bitmap);
        }
        imageView.setImageBitmap(bitmap);
        if (imageListener != null)
            imageListener.onGetImageSuccess(value.getBitmap());
    } else if (cancelPotentialWork(data, imageView)) {
        final BitmapWorkerTask task = new BitmapWorkerTask(imageView, width, height, gender, hasCover, isCircle,
                imageListener);

        final AsyncDrawable asyncDrawable = new AsyncDrawable(mResources, loadingBitmap, task);
        imageView.setImageDrawable(asyncDrawable);

        // NOTE: This uses a custom version of AsyncTask that has been
        // pulled from the
        // framework and slightly modified. Refer to the docs at the top of
        // the class
        // for more info on what was changed.
        task.executeOnExecutor(AsyncTask.DUAL_THREAD_EXECUTOR, data);
    }

}

From source file:biz.bokhorst.xprivacy.ActivityApp.java

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    final int userId = Util.getUserId(Process.myUid());

    // Check privacy service client
    if (!PrivacyService.checkClient())
        return;//from  w  w w.  j a  va  2 s  .  c om

    // Set layout
    setContentView(R.layout.restrictionlist);

    // Get arguments
    Bundle extras = getIntent().getExtras();
    if (extras == null) {
        finish();
        return;
    }

    int uid = extras.getInt(cUid);
    String restrictionName = (extras.containsKey(cRestrictionName) ? extras.getString(cRestrictionName) : null);
    String methodName = (extras.containsKey(cMethodName) ? extras.getString(cMethodName) : null);

    // Get app info
    mAppInfo = new ApplicationInfoEx(this, uid);
    if (mAppInfo.getPackageName().size() == 0) {
        finish();
        return;
    }

    // Set title
    setTitle(String.format("%s - %s", getString(R.string.app_name),
            TextUtils.join(", ", mAppInfo.getApplicationName())));

    // Handle info click
    ImageView imgInfo = (ImageView) findViewById(R.id.imgInfo);
    imgInfo.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            // Packages can be selected on the web site
            Util.viewUri(ActivityApp.this,
                    Uri.parse(String.format(ActivityShare.getBaseURL(ActivityApp.this) + "?package_name=%s",
                            mAppInfo.getPackageName().get(0))));
        }
    });

    // Display app name
    TextView tvAppName = (TextView) findViewById(R.id.tvApp);
    tvAppName.setText(mAppInfo.toString());

    // Background color
    if (mAppInfo.isSystem()) {
        LinearLayout llInfo = (LinearLayout) findViewById(R.id.llInfo);
        llInfo.setBackgroundColor(getResources().getColor(getThemed(R.attr.color_dangerous)));
    }

    // Display app icon
    final ImageView imgIcon = (ImageView) findViewById(R.id.imgIcon);
    imgIcon.setImageDrawable(mAppInfo.getIcon(this));

    // Handle icon click
    imgIcon.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            openContextMenu(imgIcon);
        }
    });

    // Display on-demand state
    final ImageView imgCbOnDemand = (ImageView) findViewById(R.id.imgCbOnDemand);
    if (PrivacyManager.isApplication(mAppInfo.getUid())
            && PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingOnDemand, true)) {
        boolean ondemand = PrivacyManager.getSettingBool(-mAppInfo.getUid(), PrivacyManager.cSettingOnDemand,
                false);
        imgCbOnDemand.setImageBitmap(ondemand ? getOnDemandCheckBox() : getOffCheckBox());

        imgCbOnDemand.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                boolean ondemand = !PrivacyManager.getSettingBool(-mAppInfo.getUid(),
                        PrivacyManager.cSettingOnDemand, false);
                PrivacyManager.setSetting(mAppInfo.getUid(), PrivacyManager.cSettingOnDemand,
                        Boolean.toString(ondemand));
                imgCbOnDemand.setImageBitmap(ondemand ? getOnDemandCheckBox() : getOffCheckBox());
                if (mPrivacyListAdapter != null)
                    mPrivacyListAdapter.notifyDataSetChanged();
            }
        });
    } else
        imgCbOnDemand.setVisibility(View.GONE);

    // Display restriction state
    swEnabled = (Switch) findViewById(R.id.swEnable);
    swEnabled.setChecked(
            PrivacyManager.getSettingBool(mAppInfo.getUid(), PrivacyManager.cSettingRestricted, true));
    swEnabled.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            PrivacyManager.setSetting(mAppInfo.getUid(), PrivacyManager.cSettingRestricted,
                    Boolean.toString(isChecked));
            if (mPrivacyListAdapter != null)
                mPrivacyListAdapter.notifyDataSetChanged();
            imgCbOnDemand.setEnabled(isChecked);
        }
    });
    imgCbOnDemand.setEnabled(swEnabled.isChecked());

    // Add context menu to icon
    registerForContextMenu(imgIcon);

    // Check if internet access
    if (!mAppInfo.hasInternet(this)) {
        ImageView imgInternet = (ImageView) findViewById(R.id.imgInternet);
        imgInternet.setVisibility(View.INVISIBLE);
    }

    // Check if frozen
    if (!mAppInfo.isFrozen(this)) {
        ImageView imgFrozen = (ImageView) findViewById(R.id.imgFrozen);
        imgFrozen.setVisibility(View.INVISIBLE);
    }

    // Display version
    TextView tvVersion = (TextView) findViewById(R.id.tvVersion);
    tvVersion.setText(TextUtils.join(", ", mAppInfo.getPackageVersionName(this)));

    // Display package name
    TextView tvPackageName = (TextView) findViewById(R.id.tvPackageName);
    tvPackageName.setText(TextUtils.join(", ", mAppInfo.getPackageName()));

    // Fill privacy list view adapter
    final ExpandableListView lvRestriction = (ExpandableListView) findViewById(R.id.elvRestriction);
    lvRestriction.setGroupIndicator(null);
    mPrivacyListAdapter = new RestrictionAdapter(R.layout.restrictionentry, mAppInfo, restrictionName,
            methodName);
    lvRestriction.setAdapter(mPrivacyListAdapter);
    if (restrictionName != null) {
        int groupPosition = new ArrayList<String>(PrivacyManager.getRestrictions(this).values())
                .indexOf(restrictionName);
        lvRestriction.expandGroup(groupPosition);
        lvRestriction.setSelectedGroup(groupPosition);
        if (methodName != null) {
            int childPosition = PrivacyManager.getHooks(restrictionName)
                    .indexOf(new Hook(restrictionName, methodName));
            lvRestriction.setSelectedChild(groupPosition, childPosition, true);
        }
    }

    // Listen for package add/remove
    IntentFilter iff = new IntentFilter();
    iff.addAction(Intent.ACTION_PACKAGE_REMOVED);
    iff.addDataScheme("package");
    registerReceiver(mPackageChangeReceiver, iff);
    mPackageChangeReceiverRegistered = true;

    // Up navigation
    getActionBar().setDisplayHomeAsUpEnabled(true);

    // Tutorial
    if (!PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingTutorialDetails, false)) {
        ((ScrollView) findViewById(R.id.svTutorialHeader)).setVisibility(View.VISIBLE);
        ((ScrollView) findViewById(R.id.svTutorialDetails)).setVisibility(View.VISIBLE);
    }
    View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            ViewParent parent = view.getParent();
            while (!parent.getClass().equals(ScrollView.class))
                parent = parent.getParent();
            ((View) parent).setVisibility(View.GONE);
            PrivacyManager.setSetting(userId, PrivacyManager.cSettingTutorialDetails, Boolean.TRUE.toString());
        }
    };
    ((Button) findViewById(R.id.btnTutorialHeader)).setOnClickListener(listener);
    ((Button) findViewById(R.id.btnTutorialDetails)).setOnClickListener(listener);

    // Process actions
    if (extras.containsKey(cAction)) {
        NotificationManager notificationManager = (NotificationManager) getSystemService(
                Context.NOTIFICATION_SERVICE);
        notificationManager.cancel(mAppInfo.getUid());
        if (extras.getInt(cAction) == cActionClear)
            optionClear();
        else if (extras.getInt(cAction) == cActionSettings)
            optionSettings();
    }

    // Annotate
    Meta.annotate(this);
}

From source file:com.concavenp.artistrymuse.fragments.BaseFragment.java

private BitmapImageViewTarget createBitmapImageViewTarget(final ImageView imageView) {

    return new BitmapImageViewTarget(imageView) {
        @Override//from  ww  w  .j a va 2 s .  c o m
        protected void setResource(Bitmap bitmap) {

            int bitmapWidth = bitmap.getWidth();
            int bitmapHeight = bitmap.getHeight();
            int borderWidthHalf = 5;
            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.arlib.floatingsearchview.FloatingSearchView.java

private void changeIcon(ImageView imageView, Drawable newIcon, boolean withAnim) {
    imageView.setImageDrawable(newIcon);
    if (withAnim) {
        ObjectAnimator fadeInVoiceInputOrClear = ObjectAnimator.ofFloat(imageView, "alpha", 0.0f, 1.0f);
        fadeInVoiceInputOrClear.start();
    } else {/*from   ww w. j a  v a  2  s  .  c o m*/
        imageView.setAlpha(1.0f);
    }
}

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.
 *//* www . j  a  v a2  s  .c  o m*/
private void forceDownload(String url, ImageView imageView, int loadingDrawable_ID, int failDrawable_ID,
        boolean isSaveLocal, ImageDownLoaderAction action) {
    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, 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:br.edu.ifpb.breath.slidingtabs.SlidingTabLayout.java

private void populateTabStrip() {
    final PagerAdapter adapter = mViewPager.getAdapter();
    final OnClickListener tabClickListener = new TabClickListener();

    for (int i = 0; i < adapter.getCount(); i++) {
        View tabView = null;/*from   w w w.  java2 s. com*/
        TextView tabTitleView = null;
        ImageView tabIconView = null;

        if (mTabViewLayoutId != 0) {
            // If there is a custom tab view layout id set, try and inflate it
            tabView = LayoutInflater.from(getContext()).inflate(mTabViewLayoutId, mTabStrip, false);
            tabTitleView = (TextView) tabView.findViewById(mTabViewTextViewId);
            tabIconView = (ImageView) tabView.findViewById(mTabViewImageViewId);
        }

        if (tabView == null && !mUseIcons) {
            tabView = createDefaultTabView(getContext(), 0);
            tabView.setAlpha(i == 0 ? 1.0f : 0.25f);
        }

        if (tabView == null && mUseIcons) {
            tabView = createDefaultTabView(getContext(), 1);
            tabView.setAlpha(i == 0 ? 1.0f : 0.25f);
        }

        if (tabTitleView == null && TextView.class.isInstance(tabView)) {
            tabTitleView = (TextView) tabView;
            tabTitleView.setAlpha(i == 0 ? 1.0f : 0.25f);
        }

        if (tabIconView == null && ImageView.class.isInstance(tabView)) {
            tabIconView = (ImageView) tabView;
            tabIconView.setAlpha(i == 0 ? 1.0f : 0.25f);
        }

        if (mDistributeEvenly) {
            LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) tabView.getLayoutParams();
            lp.width = 0;
            lp.weight = 1;
        }

        if (mUseIcons) {
            tabIconView.setVisibility(View.VISIBLE);
            if (tabTitleView != null)
                tabTitleView.setVisibility(View.GONE);

            if (mIcons.containsKey(i))
                tabIconView.setImageDrawable(mIcons.get(i));
        } else {
            tabTitleView.setVisibility(View.VISIBLE);
            if (tabIconView != null)
                tabIconView.setVisibility(View.GONE);

            tabTitleView.setText(adapter.getPageTitle(i));
            tabTitleView.setTextColor(mTextColor);
        }

        tabView.setOnClickListener(tabClickListener);
        String desc = mContentDescriptions.get(i, null);
        if (desc != null) {
            tabView.setContentDescription(desc);
        }

        mTabStrip.addView(tabView);
        if (i == mViewPager.getCurrentItem()) {
            tabView.setSelected(true);
        }
    }
}

From source file:android.support.v7.preference.Preference.java

/**
 * Binds the created View to the data for this Preference.
 * <p>// w w w . ja  v  a 2  s .  c om
 * This is a good place to grab references to custom Views in the layout and
 * set properties on them.
 * <p>
 * Make sure to call through to the superclass's implementation.
 *
 * @param holder The ViewHolder that provides references to the views to fill in. These views
 *               will be recycled, so you should not hold a reference to them after this method
 *               returns.
 */
public void onBindViewHolder(PreferenceViewHolder holder) {
    holder.itemView.setOnClickListener(mClickListener);
    holder.itemView.setId(mViewId);

    final TextView titleView = (TextView) holder.findViewById(android.R.id.title);
    if (titleView != null) {
        final CharSequence title = getTitle();
        if (!TextUtils.isEmpty(title)) {
            titleView.setText(title);
            titleView.setVisibility(View.VISIBLE);
        } else {
            titleView.setVisibility(View.GONE);
        }
    }

    final TextView summaryView = (TextView) holder.findViewById(android.R.id.summary);
    if (summaryView != null) {
        final CharSequence summary = getSummary();
        if (!TextUtils.isEmpty(summary)) {
            summaryView.setText(summary);
            summaryView.setVisibility(View.VISIBLE);
        } else {
            summaryView.setVisibility(View.GONE);
        }
    }

    final ImageView imageView = (ImageView) holder.findViewById(android.R.id.icon);
    if (imageView != null) {
        if (mIconResId != 0 || mIcon != null) {
            if (mIcon == null) {
                mIcon = ContextCompat.getDrawable(getContext(), mIconResId);
            }
            if (mIcon != null) {
                imageView.setImageDrawable(mIcon);
            }
        }
        imageView.setVisibility(mIcon != null ? View.VISIBLE : View.GONE);
    }

    View imageFrame = holder.findViewById(R.id.icon_frame);
    if (imageFrame == null) {
        imageFrame = holder.findViewById(AndroidResources.ANDROID_R_ICON_FRAME);
    }
    if (imageFrame != null) {
        imageFrame.setVisibility(mIcon != null ? View.VISIBLE : View.GONE);
    }

    if (mShouldDisableView) {
        setEnabledStateOnViews(holder.itemView, isEnabled());
    } else {
        setEnabledStateOnViews(holder.itemView, true);
    }

    final boolean selectable = isSelectable();
    holder.itemView.setFocusable(selectable);
    holder.itemView.setClickable(selectable);

    holder.setDividerAllowedAbove(selectable);
    holder.setDividerAllowedBelow(selectable);
}

From source file:com.ifeng.util.imagecache.ImageWorker.java

/**
 * Load an image specified by the data parameter into an ImageView (override
 * {@link ImageWorker#processBitmap(Object)} to define the processing
 * logic). A memory and disk cache will be used if an {@link ImageCache} has
 * been added using// w w  w  .j  a va  2 s.co m
 * {@link ImageWorker#addImageCache(FragmentManager, ImageCache.ImageCacheParams)}
 * . If the image is found in the memory cache, it is set immediately,
 * otherwise an {@link AsyncTask} will be created to asynchronously load the
 * bitmap.
 * 
 * @param item
 *            The loadtask of the image to download.
 * @param imageView
 *            The ImageView to bind the downloaded image to.
 */
final protected void loadImageInternal(BitmapTaskItem item, ImageView imageView) {
    if (item == null || item.mDataSource == null || imageView == null) {
        return;
    }

    // ?
    if (item.mDataSource instanceof String && TextUtils.isEmpty((CharSequence) item.mDataSource)) {
        return;
    }
    // resId?s
    if (item.mDataSource instanceof Integer && (Integer) item.mDataSource == 0) {
        return;
    }

    BitmapDrawable value = null;

    if (mImageCache != null) {
        value = mImageCache.getBitmapFromMemCache(String.valueOf(item.mDataSource));
    }

    if (value != null) {
        // Bitmap found in memory cache
        // Bug fix by XuWei 2013-09-09
        // Drawable?bug?ViewDrawable??Drawable
        Drawable copyDrawable = new BitmapDrawable(mResources, value.getBitmap());
        imageView.setImageDrawable(copyDrawable);
    } else if (cancelPotentialWork(item.mDataSource, imageView)) {

        byte[] chunk = null;
        if (mLoadingBitmap != null) {
            chunk = mLoadingBitmap.getNinePatchChunk();
        }

        final BitmapWorkerTask task = new BitmapWorkerTask(imageView);
        if (chunk == null) {
            final AsyncBitmapDrawable asyncBitmapDrawable = new AsyncBitmapDrawable(mResources, mLoadingBitmap,
                    task);
            imageView.setImageDrawable(asyncBitmapDrawable);
        } else {
            final AsyncNinePatchDrawable.NinePatchChunk npc = AsyncNinePatchDrawable.NinePatchChunk
                    .deserialize(chunk);
            final AsyncNinePatchDrawable asyncNinePatchDrawable = new AsyncNinePatchDrawable(mResources,
                    mLoadingBitmap, chunk, npc.mPaddings, null, task);
            imageView.setImageDrawable(asyncNinePatchDrawable);
        }

        // NOTE: This uses a custom version of AsyncTask that has been
        // pulled from the
        // framework and slightly modified. Refer to the docs at the top of
        // the class
        // for more info on what was changed.
        task.executeOnExecutor(mExecutor, item);
    }
}

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 w w w.  j  a v  a  2  s. co m*/
private void forceDownload(String url, ImageView imageView, int loadingDrawable_ID, int failDrawable_ID,
        boolean isSaveLocal, ImageDownLoaderAction action) {
    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, 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.benefit.buy.library.http.query.AbstractAQuery.java

/**
 * Set the image of an ImageView./*w ww . j  a  v  a  2  s .c  o  m*/
 * @param drawable the drawable
 * @return self
 * @see testImage2
 */
public T image(Drawable drawable) {
    if (view instanceof ImageView) {
        ImageView iv = (ImageView) view;
        iv.setTag(Constants.TAG_URL, null);
        iv.setImageDrawable(drawable);
    }
    return self();
}