Example usage for android.widget ImageView getContext

List of usage examples for android.widget ImageView getContext

Introduction

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

Prototype

@ViewDebug.CapturedViewProperty
public final Context getContext() 

Source Link

Document

Returns the context the view is running in, through which it can access the current theme, resources, etc.

Usage

From source file:com.synconset.ImageFetcher.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  ww. j  av a2 s . com*/
private void forceDownload(Integer position, ImageView imageView, int rotate) {
    if (position == null) {
        imageView.setImageDrawable(null);
        return;
    }

    if (cancelPotentialDownload(position, imageView)) {
        BitmapFetcherTask task = new BitmapFetcherTask(imageView.getContext(), imageView, rotate);
        DownloadedDrawable downloadedDrawable = new DownloadedDrawable(imageView.getContext(), task, origId);
        imageView.setImageDrawable(downloadedDrawable);
        imageView.setMinimumHeight(colWidth);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            task.executeOnExecutor(executor, position);
        } else {
            try {
                task.execute(position);
            } catch (RejectedExecutionException e) {
                // Oh :(
            }
        }

    }
}

From source file:com.tangjd.displayingbitmaps.util.ImageWorker.java

/**
 * Called when the processing is complete and the final drawable should be
 * set on the ImageView./*from w w  w  .  j a va 2s.  co m*/
 *
 * @param imageView
 * @param drawable
 */
@SuppressWarnings("deprecation")
private void setImageDrawable(ImageView imageView, Drawable drawable) {
    if (mFadeInBitmap) {
        // Transition drawable with a transparent drawable and the final drawable
        final TransitionDrawable td = new TransitionDrawable(new Drawable[] {
                new ColorDrawable(imageView.getContext().getResources().getColor(android.R.color.transparent)),
                drawable });
        // Set background to loading bitmap
        imageView.setBackgroundDrawable(new BitmapDrawable(mResources, mLoadingBitmap));

        imageView.setImageDrawable(td);
        td.startTransition(FADE_IN_TIME);
    } else {
        imageView.setImageDrawable(drawable);
    }
}

From source file:fr.eoidb.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.
 *//*  w w  w.ja  v a  2  s  .c  o  m*/
private void forceDownload(String url, ImageView imageView, String cookie) {
    // State sanity: url is guaranteed to never be null in DownloadedDrawable and cache keys.
    if (url == null) {
        imageView.setImageDrawable(null);
        return;
    }

    if (cancelPotentialDownload(url, imageView)) {
        BitmapDownloaderTask task = new BitmapDownloaderTask(imageView);
        DownloadedDrawable downloadedDrawable = new DownloadedDrawable(task,
                imageView.getContext().getResources());
        imageView.setImageDrawable(downloadedDrawable);
        task.execute(url, cookie);
    }
}

From source file:com.c4mprod.utils.ImageDownloader.java

/**
 * Download the specified image from the Internet and binds it to the provided ImageView. The
 * binding is immediate if the image is found in the cache and will be done asynchronously
 * otherwise. A null bitmap will be associated to the ImageView if an error occurs.
 * //w ww. j a  v a  2s .  c  om
 * @param url
 * @param imageView
 * @param subfolder
 *            the subfolder in sdcard cache
 * 
 */
public void download(String url, ImageView imageView, String subfolder) {
    if (subfolder != null) {
        mSubfolder = "/" + subfolder;
    } else {
        mSubfolder = "";
    }

    mfolder = Environment.getExternalStorageDirectory().getPath() + "/Android/data/"
            + imageView.getContext().getPackageName() + "/files/images" + mSubfolder;

    if (Environment.MEDIA_MOUNTED.equals(state)) {
        // We can read and write the media
        mExternalStorageAvailable = mExternalStorageWriteable = true;
        try {
            (new File(mfolder)).mkdirs();
            (new File(mfolder + "/.nomedia")).createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
        // We can only read the media
        mExternalStorageAvailable = true;
        mExternalStorageWriteable = false;
    } else {
        // Something else is wrong. It may be one of many other states, but
        // all we need
        // to know is we can neither read nor write
        mExternalStorageAvailable = mExternalStorageWriteable = false;
    }

    resetPurgeTimer();
    Bitmap bitmap = getBitmapFromCache(url);

    if (bitmap == null) {
        forceDownload(url, imageView);
    } else {
        cancelPotentialDownload(url, imageView);
        imageView.setImageBitmap(bitmap);
        imageView.setBackgroundDrawable(null);
        if (listener != null) {
            listener.onImageDownloaded(imageView, url, mfolder + "/" + URLEncoder.encode(url),
                    imageView.getDrawable().getIntrinsicWidth(), imageView.getDrawable().getIntrinsicWidth());
        }
    }
}

From source file:com.fa.mastodon.activity.MainActivity.java

private void setupDrawer() {
    headerResult = new AccountHeaderBuilder().withActivity(this).withSelectionListEnabledForSingleProfile(false)
            .withDividerBelowHeader(false)
            .withOnAccountHeaderProfileImageListener(new AccountHeader.OnAccountHeaderProfileImageListener() {
                @Override//from   ww  w . j av  a2  s.c  o  m
                public boolean onProfileImageClick(View view, IProfile profile, boolean current) {
                    if (current && loggedInAccountId != null) {
                        Intent intent = new Intent(MainActivity.this, AccountActivity.class);
                        intent.putExtra("id", loggedInAccountId);
                        startActivity(intent);
                        return true;
                    }
                    return false;
                }

                @Override
                public boolean onProfileImageLongClick(View view, IProfile profile, boolean current) {
                    return false;
                }
            }).withCompactStyle(true).build();
    headerResult.getView().findViewById(R.id.material_drawer_account_header_current)
            .setContentDescription(getString(R.string.action_view_profile));

    DrawerImageLoader.init(new AbstractDrawerImageLoader() {
        @Override
        public void set(ImageView imageView, Uri uri, Drawable placeholder) {
            Picasso.with(imageView.getContext()).load(uri).placeholder(placeholder).into(imageView);
        }

        @Override
        public void cancel(ImageView imageView) {
            Picasso.with(imageView.getContext()).cancelRequest(imageView);
        }
    });

    VectorDrawableCompat muteDrawable = VectorDrawableCompat.create(getResources(), R.drawable.ic_mute_24dp,
            getTheme());
    ThemeUtils.setDrawableTint(this, muteDrawable, R.attr.toolbar_icon_tint);

    drawer = new DrawerBuilder().withActivity(this)
            //.withToolbar(toolbar)
            .withAccountHeader(headerResult).withTranslucentStatusBar(false).withHasStableIds(true)
            .withSelectedItem(-1)
            .addDrawerItems(
                    new PrimaryDrawerItem().withIdentifier(8).withName(getString(R.string.discover))
                            .withIcon(GoogleMaterial.Icon.gmd_explore),
                    new PrimaryDrawerItem().withIdentifier(0).withName(getString(R.string.action_edit_profile))
                            .withSelectable(false).withIcon(GoogleMaterial.Icon.gmd_face),
                    new PrimaryDrawerItem().withIdentifier(1)
                            .withName(getString(R.string.action_view_favourites)).withSelectable(false)
                            .withIcon(GoogleMaterial.Icon.gmd_star),
                    new PrimaryDrawerItem().withIdentifier(2).withName(getString(R.string.action_view_mutes))
                            .withSelectable(false).withIcon(GoogleMaterial.Icon.gmd_volume_mute),
                    new PrimaryDrawerItem().withIdentifier(3).withName(getString(R.string.action_view_blocks))
                            .withSelectable(false).withIcon(GoogleMaterial.Icon.gmd_block),
                    new DividerDrawerItem(),
                    new PrimaryDrawerItem().withIdentifier(4)
                            .withName(getString(R.string.action_view_preferences)).withSelectable(false)
                            .withIcon(GoogleMaterial.Icon.gmd_settings),
                    new PrimaryDrawerItem().withIdentifier(6).withName(getString(R.string.action_logout))
                            .withSelectable(false).withIcon(GoogleMaterial.Icon.gmd_power_settings_new))
            .withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
                @Override
                public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
                    if (drawerItem != null) {
                        long drawerItemIdentifier = drawerItem.getIdentifier();

                        if (drawerItemIdentifier == 0) {
                            Intent intent = new Intent(MainActivity.this, EditProfileActivity.class);
                            startActivity(intent);
                        } else if (drawerItemIdentifier == 1) {
                            Intent intent = new Intent(MainActivity.this, FavoritesActivity.class);
                            startActivity(intent);
                        } else if (drawerItemIdentifier == 2) {
                            Intent intent = new Intent(MainActivity.this, AccountListActivity.class);
                            intent.putExtra("type", AccountListActivity.Type.MUTES);
                            startActivity(intent);
                        } else if (drawerItemIdentifier == 3) {
                            Intent intent = new Intent(MainActivity.this, AccountListActivity.class);
                            intent.putExtra("type", AccountListActivity.Type.BLOCKS);
                            startActivity(intent);
                        } else if (drawerItemIdentifier == 4) {
                            Intent intent = new Intent(MainActivity.this, PreferencesActivity.class);
                            startActivity(intent);
                        } else if (drawerItemIdentifier == 5) {
                            Intent intent = new Intent(MainActivity.this, AboutActivity.class);
                            startActivity(intent);
                        } else if (drawerItemIdentifier == 6) {
                            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                            builder.setTitle(R.string.areyousure);

                            builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    logout();
                                }
                            });
                            builder.setNegativeButton(R.string.abort, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.cancel();
                                }
                            });

                            builder.show();

                            logout();
                        } else if (drawerItemIdentifier == 7) {
                            Intent intent = new Intent(MainActivity.this, AccountListActivity.class);
                            intent.putExtra("type", AccountListActivity.Type.FOLLOW_REQUESTS);
                            startActivity(intent);
                        } else if (drawerItemIdentifier == 8) {
                            drawer.closeDrawer();
                        }
                    }

                    return false;
                }
            }).build();
    drawer.setSelection(8);
}

From source file:com.benefit.buy.library.http.query.callback.BitmapAjaxCallback.java

private static void setBmAnimate(ImageView iv, Bitmap bm, Bitmap preset, int fallback, int animation,
        float ratio, float anchor, int source) {
    bm = filter(iv, bm, fallback);//from w w  w  .ja v  a 2s  .com
    if (bm == null) {
        iv.setImageBitmap(null);
        return;
    }
    Drawable d = makeDrawable(iv, bm, ratio, anchor);
    Animation anim = null;
    if (fadeIn(animation, source)) {
        if (preset == null) {
            anim = new AlphaAnimation(0, 1);
            anim.setInterpolator(new DecelerateInterpolator());
            anim.setDuration(FADE_DUR);
        } else {
            Drawable pd = makeDrawable(iv, preset, ratio, anchor);
            Drawable[] ds = new Drawable[] { pd, d };
            TransitionDrawable td = new TransitionDrawable(ds);
            td.setCrossFadeEnabled(true);
            td.startTransition(FADE_DUR);
            d = td;
        }
    } else if (animation > 0) {
        anim = AnimationUtils.loadAnimation(iv.getContext(), animation);
    }
    iv.setImageDrawable(d);
    if (anim != null) {
        anim.setStartTime(AnimationUtils.currentAnimationTimeMillis());
        iv.startAnimation(anim);
    } else {
        iv.setAnimation(null);
    }
}

From source file:com.landenlabs.all_devtool.IconBaseFragment.java

/**
 * Show a 'StateListDrawable' information
 *
 * @param imageView/*from www .j av a  2 s  .co  m*/
 * @param row1
 * @param row2
 * @param stateListDrawable
 * @param state
 * @param desc
 * @param stateIcons
 */
private void showStateIcon(final ImageView imageView, TableRow row1, TableRow row2,
        StateListDrawable stateListDrawable, int state, String desc, Set<Drawable> stateIcons) {

    stateListDrawable.setState(new int[] { state });
    Drawable stateD = stateListDrawable.getCurrent();
    if (stateD != null && !stateIcons.contains(stateD)) {
        stateIcons.add(stateD);
        ImageButton stateImageView = new ImageButton(imageView.getContext());
        Drawable[] drawables = new Drawable[] { stateD,
                getResources().getDrawable(R.drawable.button_border_sel) };

        LayerDrawable layerDrawable = new LayerDrawable(drawables);
        stateImageView.setImageDrawable(layerDrawable);
        //   stateImageView.setBackgroundResource(R.drawable.button_border_sel);
        stateImageView.setPadding(10, 10, 10, 10);
        stateImageView.setMinimumHeight(8);
        stateImageView.setMinimumWidth(8);
        stateImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                imageView.setImageDrawable(((ImageView) v).getDrawable());
            }
        });

        TextView stateTextView = new TextView(imageView.getContext());
        stateTextView.setText(desc);
        stateTextView.setTextSize(12);
        stateTextView.setGravity(Gravity.CENTER);

        row1.addView(stateTextView);
        row2.addView(stateImageView);
    }
}

From source file:com.fa.mastodon.activity.EditProfileActivity.java

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

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);// www.  j  av  a 2  s .c o  m
    ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) {
        actionBar.setTitle(getString(R.string.title_edit_profile));
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setDisplayShowHomeEnabled(true);
    }

    if (savedInstanceState != null) {
        priorDisplayName = savedInstanceState.getString("priorDisplayName");
        priorNote = savedInstanceState.getString("priorNote");
        isAlreadySaving = savedInstanceState.getBoolean("isAlreadySaving");
        currentlyPicking = (PickType) savedInstanceState.getSerializable("currentlyPicking");
        avatarBase64 = savedInstanceState.getString("avatarBase64");
        headerBase64 = savedInstanceState.getString("headerBase64");
    } else {
        priorDisplayName = null;
        priorNote = null;
        isAlreadySaving = false;
        currentlyPicking = PickType.NOTHING;
        avatarBase64 = null;
        headerBase64 = null;
    }

    avatarButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onMediaPick(PickType.AVATAR);
        }
    });
    headerButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onMediaPick(PickType.HEADER);
        }
    });

    avatarPreview.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            avatarPreview.setImageBitmap(null);
            avatarPreview.setVisibility(View.INVISIBLE);
            avatarBase64 = null;
        }
    });
    headerPreview.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            headerPreview.setImageBitmap(null);
            headerPreview.setVisibility(View.INVISIBLE);
            headerBase64 = null;
        }
    });

    mastodonAPI.accountVerifyCredentials().enqueue(new Callback<Account>() {
        @Override
        public void onResponse(Call<Account> call, Response<Account> response) {
            if (!response.isSuccessful()) {
                onAccountVerifyCredentialsFailed();
                return;
            }
            Account me = response.body();
            priorDisplayName = me.getDisplayName();
            priorNote = me.note.toString();
            CircularImageView avatar = (CircularImageView) findViewById(R.id.edit_profile_avatar_preview);
            ImageView header = (ImageView) findViewById(R.id.edit_profile_header_preview);

            displayNameEditText.setText(priorDisplayName);
            noteEditText.setText(priorNote);
            Picasso.with(avatar.getContext()).load(me.avatar).placeholder(R.drawable.avatar_default)
                    .error(R.drawable.avatar_error).into(avatar);
            Picasso.with(header.getContext()).load(me.header).placeholder(R.drawable.account_header_default)
                    .into(header);
        }

        @Override
        public void onFailure(Call<Account> call, Throwable t) {
            onAccountVerifyCredentialsFailed();
        }
    });
}

From source file:info.papdt.blacklight.support.adapter.WeiboAdapter.java

private void bindMultiPicLayout(ViewHolder h, MessageModel msg, boolean showPic) {
    if (showPic && h.getItemViewType() % 10 > 0) {
        LinearLayout container = h.pics;

        int numChilds = h.getItemViewType() % 10;

        for (int i = 0; i < numChilds; i++) {
            ImageView iv = (ImageView) container.getChildAt(i);

            String url = null;//from w  ww. j a  v  a  2  s  .co  m
            if (msg.hasMultiplePictures()) {
                url = msg.pic_urls.get(i).getThumbnail();
            } else if (i == 0) {
                url = msg.thumbnail_pic;
            }

            Picasso.with(iv.getContext()).load(url).fit().centerCrop().into(iv);

            iv.setTag(TAG_MSG, msg);
        }
    }
}

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 www  .  ja  v  a2s .c om
    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");
}