Example usage for android.widget ImageView setImageBitmap

List of usage examples for android.widget ImageView setImageBitmap

Introduction

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

Prototype

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

Source Link

Document

Sets a Bitmap as the content of this ImageView.

Usage

From source file:com.androidtest.HttpParser2.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.  j a  v a 2s. com
private void forceDownload(String url, ImageView imageView) {
    // 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)) {
        //Log.d(TAG,"Mode : "+mode);
        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);
            task.execute(url);
            break;

        case CORRECT:
            task = new BitmapDownloaderTask(imageView);
            DownloadedDrawable downloadedDrawable = new DownloadedDrawable(task);
            imageView.setImageDrawable(downloadedDrawable);
            imageView.setMinimumHeight(156);
            task.execute(url);
            break;
        }
    }
}

From source file:com.zhihuigu.sosoOffice.utils.ImageDownloaderUrl.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  va2  s .c o m
 * @param url
 *            The URL of the image to download.
 * @param imageView
 *            The ImageView to bind the downloaded image to.
 */
public void download(String url, File file, String sql, ImageView imageView) {
    resetPurgeTimer(); // 
    Bitmap bitmap = getBitmapFromCache(url);
    if (connection_count > connection_count_totle) {
        return;
    }
    if (bitmap == null) {
        System.out.println("1");
        forceDownload(url, file, sql, imageView);
    } else {
        System.out.println("2");
        cancelPotentialDownload(url, imageView);
        imageView.setImageBitmap(bitmap);
    }
}

From source file:org.ros.android.app_chooser.ExchangeActivity.java

public void updateAppDetails() {
    final AppManager man = appManager;
    if (man == null) {
        return;//from  www  .  j  a  v  a2  s.  c o  m
    }
    man.getAppDetails(appSelected, new ServiceResponseListener<GetAppDetails.Response>() {
        @Override
        public void onSuccess(GetAppDetails.Response message) {
            final ExchangeApp app = message.app;
            if (app == null) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        revertToState();
                        appDetailView.setVisibility(appDetailView.GONE);
                        new AlertDialog.Builder(ExchangeActivity.this).setTitle("Error on Details Update!")
                                .setCancelable(false)
                                .setMessage("Failed: cannot contact robot! Null application returned")
                                .setNeutralButton("Ok", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                    }
                                }).create().show();
                    }
                });
                return;
            }
            Bitmap bitmap = null;
            if (app.icon.data.length > 0 && app.icon.format != null
                    && (app.icon.format.equals("jpeg") || app.icon.format.equals("png"))) {
                bitmap = BitmapFactory.decodeByteArray(app.icon.data, 0, app.icon.data.length);
            }
            final Bitmap iconBitmap = bitmap;
            Log.i("RosAndroid", "GetInstallationState.Response: " + availableAppsCache.size() + " apps");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ImageView iv = (ImageView) ExchangeActivity.this.findViewById(R.id.exchange_icon);
                    if (iconBitmap != null) {
                        iv.setImageBitmap(iconBitmap);
                    } else {
                        iv.setImageResource(R.drawable.icon);
                    }
                    exchangeAppDetailTextView.setText(app.description.toString());
                    update(availableAppsCache, installedAppsCache);
                }
            });
        }

        @Override
        public void onFailure(final RemoteException e) {
            e.printStackTrace();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    revertToState();
                    appDetailView.setVisibility(appDetailView.GONE);
                    new AlertDialog.Builder(ExchangeActivity.this).setTitle("Error on Details Update!")
                            .setCancelable(false).setMessage("Failed: cannot contact robot: " + e.toString())
                            .setNeutralButton("Ok", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                }
                            }).create().show();
                }
            });
        }
    });
}

From source file:android.com.example.contactslist.util.ImageLoader.java

/**
 * Called when the processing is complete and the final bitmap should be set on the ImageView.
 *
 * @param imageView The ImageView to set the bitmap to.
 * @param bitmap The new bitmap to set./*w  ww .  j a va 2  s.c  om*/
 */
private void setImageBitmap(ImageView imageView, Bitmap bitmap) {
    if (mFadeInBitmap) {
        // Transition drawable to fade from loading bitmap to final bitmap
        final TransitionDrawable td = new TransitionDrawable(new Drawable[] {
                new ColorDrawable(android.R.color.transparent), new BitmapDrawable(mResources, bitmap) });
        imageView.setBackgroundDrawable(imageView.getDrawable());
        imageView.setImageDrawable(td);
        td.startTransition(FADE_IN_TIME);
    } else {
        imageView.setImageBitmap(bitmap);
    }
}

From source file:app.sunstreak.yourpisd.LoginActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login_new);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    if (toolbar != null) {
        setSupportActionBar(toolbar);/*from w  w  w  .ja  va  2s .  co  m*/
    }
    final SharedPreferences sharedPrefs = getPreferences(Context.MODE_PRIVATE);
    Display display = getWindowManager().getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);
    height = size.y;
    mLoginFormView = findViewById(R.id.login_form);
    mLoginStatusView = (LinearLayout) findViewById(R.id.login_status);
    mLoginStatusMessageView = (TextView) findViewById(R.id.login_status_message);

    if (DateHelper.isAprilFools()) {
        LinearLayout container = (LinearLayout) mLoginFormView.findViewById(R.id.container);
        ImageView logo = (ImageView) container.findViewById(R.id.logo);
        InputStream is;
        try {
            is = getAssets().open("doge.png");
            logo.setImageBitmap(BitmapFactory.decodeStream(is));
            is.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    mAutoLogin = sharedPrefs.getBoolean("auto_login", false);
    System.out.println(mAutoLogin);

    session = ((YPApplication) getApplication()).session;

    try {
        boolean refresh = getIntent().getExtras().getBoolean("Refresh");

        if (refresh) {
            mEmail = session.getUsername();
            mPassword = session.getPassword();
            showProgress(true);
            mAuthTask = new UserLoginTask();
            mAuthTask.execute((Void) null);

            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(mPasswordView.getWindowToken(), 0);
        } else
            mLoginFormView.setVisibility(View.VISIBLE);
    } catch (NullPointerException e) {
        // Keep going.
    }

    if (sharedPrefs.getBoolean("patched", false)) {
        SharedPreferences.Editor editor = sharedPrefs.edit();
        editor.remove("password");
        editor.putBoolean("patched", true);
        editor.commit();
    }

    if (!sharedPrefs.getBoolean("AcceptedUserAgreement", false)) {

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(getResources().getString(R.string.user_agreement_title));
        builder.setMessage(getResources().getString(R.string.user_agreement));
        // Setting Positive "Yes" Button
        builder.setPositiveButton("Agree", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                sharedPrefs.edit().putBoolean("AcceptedUserAgreement", true).commit();
                dialog.cancel();
            }
        });

        // Setting Negative "NO" Button
        builder.setNegativeButton("Disagree", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // Write your code here to invoke NO event
                sharedPrefs.edit().putBoolean("AcceptedUserAgreement", false).commit();
                Toast.makeText(LoginActivity.this, "Quitting app", Toast.LENGTH_SHORT).show();
                finish();
            }
        });

        AlertDialog alertDialog = builder.create();
        alertDialog.show();
    }

    // Set up the remember_password CheckBox
    mRememberPasswordCheckBox = (CheckBox) findViewById(R.id.remember_password);
    mRememberPasswordCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            mRememberPassword = isChecked;
        }
    });

    mRememberPassword = sharedPrefs.getBoolean("remember_password", false);
    mRememberPasswordCheckBox.setChecked(mRememberPassword);

    // Set up the auto_login CheckBox
    mAutoLoginCheckBox = (CheckBox) findViewById(R.id.auto_login);
    mAutoLoginCheckBox.setChecked(mAutoLogin);
    mAutoLoginCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton button, boolean isChecked) {
            mAutoLogin = isChecked;
            if (isChecked) {
                mRememberPasswordCheckBox.setChecked(true);
            }
        }

    });

    // Set up the login form.
    mEmailView = (EditText) findViewById(R.id.email);

    mPasswordView = (EditText) findViewById(R.id.password);
    mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
            if (id == R.id.login || id == EditorInfo.IME_NULL) {
                attemptLogin();
                return true;
            }
            return false;
        }
    });

    //Load stored username/password
    mEmailView.setText(sharedPrefs.getString("email", mEmail));
    mPasswordView.setText(new String(Base64.decode(sharedPrefs.getString("e_password", ""), Base64.DEFAULT)));
    // If the password was not saved, give focus to the password.
    if (mPasswordView.getText().equals(""))
        mPasswordView.requestFocus();

    mLoginFormView = findViewById(R.id.login_form);
    mLoginStatusView = (LinearLayout) findViewById(R.id.login_status);
    mLoginStatusMessageView = (TextView) findViewById(R.id.login_status_message);

    findViewById(R.id.sign_in_button).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            attemptLogin();
        }
    });
    findViewById(R.id.sign_in_button).setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(mPasswordView.getWindowToken(), 0);
            return false;
        }
    });
    mLoginFormView.setVisibility(View.VISIBLE);
    // Login if auto-login is checked.
    if (mAutoLogin)
        attemptLogin();
}

From source file:de.golov.zeitgeistreich.ZeitGeistReichActivity.java

/** Called when the activity is first created. */
@Override//ww  w  .j  av a 2  s .  co m
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    final ImageView imagePreview = (ImageView) findViewById(R.id.ImagePreview);
    Intent intent = getIntent();
    Bundle extras = intent.getExtras();
    Uri mImageUri = null;
    if (Intent.ACTION_SEND.equals(intent.getAction()) && extras != null) {
        if (extras.containsKey(Intent.EXTRA_STREAM)) {
            mImageUri = (Uri) extras.getParcelable(Intent.EXTRA_STREAM);
            if (mImageUri != null) {
                int origId = Integer.parseInt(mImageUri.getLastPathSegment());
                Bitmap bitmap = MediaStore.Images.Thumbnails.getThumbnail(getContentResolver(), origId,
                        MediaStore.Images.Thumbnails.MINI_KIND, (BitmapFactory.Options) null);
                imagePreview.setImageBitmap(bitmap);
            }
        }
    }

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line,
            tag_suggests);
    final MultiAutoCompleteTextView textView = (MultiAutoCompleteTextView) findViewById(R.id.TagEditView);
    textView.setAdapter(adapter);
    textView.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());

    final Button button = (Button) findViewById(R.id.ZeitgeistSubmit);
    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            submitImage(textView.getText().toString());
        }
    });
}

From source file:com.mobicage.rogerthat.GroupDetailActivity.java

private void updateView() {
    T.UI();//from   ww  w  .  ja v a  2  s.  com
    final ImageView image = (ImageView) findViewById(R.id.friend_avatar);
    final ImageView newGroupAvatar = ((ImageView) findViewById(R.id.update_group_avatar_img));

    final Bitmap avatarBitmap = mFriendsPlugin.toGroupBitmap(mGroup.avatar);
    image.setImageBitmap(avatarBitmap);
    newGroupAvatar.setImageBitmap(avatarBitmap);

    final TextView nameView = (TextView) findViewById(R.id.friend_name);
    nameView.setText(mGroup.name);
    mUpdateGroupName.setText(mGroup.name);

    final Button saveBtn = (Button) findViewById(R.id.save_group);
    saveBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mEditing) {
                if (mUpdateGroupName.getText().length() == 0) {
                    UIUtils.showDialog(GroupDetailActivity.this, null, R.string.name_required);
                    return;
                }

                if (mGroup.members.size() == 0) {
                    UIUtils.showDialog(GroupDetailActivity.this, null, R.string.members_are_required);
                    return;
                }
            }
            updateGroupLayout(!mEditing);
            // We need to remove all the views because of a bug in samsung galaxy S2
            // which does not remove items in the listview if smaller then the screen
            mLinearLayout.removeAllViews();
            mLinearLayout = (LinearLayout) LayoutInflater.from(GroupDetailActivity.this)
                    .inflate(R.layout.group_detail, null);
            setContentView(mLinearLayout);

            // END
            updateView();
        }
    });

    final ImageView editBtn = (ImageView) findViewById(R.id.edit_group);
    editBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            T.UI();
            updateGroupLayout(!mEditing);
            updateView();
        }
    });

    final Button cancelBtn = (Button) findViewById(R.id.cancel);
    cancelBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            T.UI();
            if (mIsNewGroup) {
                mFriendsPlugin.getStore().deleteGroup(mGroup.guid);

                Intent intent = new Intent(FriendsPlugin.GROUP_REMOVED);
                intent.putExtra("guid", mGroup.guid);
                mService.sendBroadcast(intent);
                mGroup = null;
            }
            finish();
        }
    });

    initListView();

    setTitle(mGroup.name);
}

From source file:com.blueverdi.rosietheriveter.PhotoViewActivity.java

private void slide(final ImageView v, final Bitmap new_image, final int in, final int out, final TextView view,
        final String string) {
    final Animation anim_out = AnimationUtils.loadAnimation(this, out);
    final Animation anim_in = AnimationUtils.loadAnimation(this, in);
    anim_out.setAnimationListener(new AnimationListener() {
        @Override//from   www.j a  v  a2 s . c om
        public void onAnimationStart(Animation animation) {
        }

        @Override
        public void onAnimationRepeat(Animation animation) {
        }

        @Override
        public void onAnimationEnd(Animation animation) {
            v.setImageBitmap(new_image);
            anim_in.setAnimationListener(new AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {
                }

                @Override
                public void onAnimationRepeat(Animation animation) {
                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    view.setText(string);
                }
            });
            v.startAnimation(anim_in);
        }
    });
    v.startAnimation(anim_out);
}

From source file:com.haipeng.libraryforandroid.cacheormemory.imageload.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 set using {@link ImageWorker#setImageCache(ImageCache)}. 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.
 * //from  www .j a v a  2s  .c  o m
 * @param data
 *            The URL of the image to download.
 * @param imageView
 *            The ImageView to bind the downloaded image to.
 * @param loadImgViaMobile 
 *             ?true
 */
public void loadImage(Object data, ImageView imageView, LoadingIndicatorView indicatorView,
        boolean loadImgViaMobile) {

    if (data == null || TextUtils.isEmpty(data.toString().trim())) {
        if (mLoadingBitmap != null && imageView != null)
            imageView.setImageBitmap(mLoadingBitmap);
        return;
    }

    Bitmap bitmap = null;

    if (mImageCache != null) {
        bitmap = mImageCache.getBitmapFromMemCache(String.valueOf(data));
    }

    if (bitmap != null) {
        // Bitmap found in memory cache
        notifyLoadComplete(String.valueOf(data), bitmap, imageView);
        imageView.setImageBitmap(bitmap);
        indicatorView.onProgressUpdate(100);
        indicatorView.setAsyncIndicator(null);
    } else if (cancelPotentialWork(data, imageView)) {
        final BitmapWorkerTask task = new BitmapWorkerTask(imageView, indicatorView, loadImgViaMobile);
        final AsyncDrawable asyncDrawable = new AsyncDrawable(mResources, mLoadingBitmap, task);
        imageView.setImageDrawable(asyncDrawable);

        final AsyncIndicator asyncIndicator = new AsyncIndicator(task);
        indicatorView.setAsyncIndicator(asyncIndicator);

        // 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:com.coact.kochzap.CaptureActivity.java

private void handleDecodeInternally(Result rawResult, ResultHandler resultHandler, Bitmap barcode) {

    maybeSetClipboard(resultHandler);//  w w w  .jav  a2 s  .  c om

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    if (resultHandler.getDefaultButtonID() != null
            && prefs.getBoolean(PreferencesActivity.KEY_AUTO_OPEN_WEB, false)) {
        resultHandler.handleButtonPress(resultHandler.getDefaultButtonID());
        return;
    }

    statusView.setVisibility(View.GONE);
    viewfinderView.setVisibility(View.GONE);
    resultView.setVisibility(View.VISIBLE);

    ImageView barcodeImageView = (ImageView) findViewById(R.id.barcode_image_view);
    if (barcode == null) {
        barcodeImageView.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.launcher_icon));
    } else {
        barcodeImageView.setImageBitmap(barcode);
    }

    TextView formatTextView = (TextView) findViewById(R.id.format_text_view);
    formatTextView.setText(rawResult.getBarcodeFormat().toString());

    TextView typeTextView = (TextView) findViewById(R.id.type_text_view);
    typeTextView.setText(resultHandler.getType().toString());

    DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
    TextView timeTextView = (TextView) findViewById(R.id.time_text_view);
    timeTextView.setText(formatter.format(rawResult.getTimestamp()));

    TextView metaTextView = (TextView) findViewById(R.id.meta_text_view);
    View metaTextViewLabel = findViewById(R.id.meta_text_view_label);
    metaTextView.setVisibility(View.GONE);
    metaTextViewLabel.setVisibility(View.GONE);
    Map<ResultMetadataType, Object> metadata = rawResult.getResultMetadata();
    if (metadata != null) {
        StringBuilder metadataText = new StringBuilder(20);
        for (Map.Entry<ResultMetadataType, Object> entry : metadata.entrySet()) {
            if (DISPLAYABLE_METADATA_TYPES.contains(entry.getKey())) {
                metadataText.append(entry.getValue()).append('\n');
            }
        }
        if (metadataText.length() > 0) {
            metadataText.setLength(metadataText.length() - 1);
            metaTextView.setText(metadataText);
            metaTextView.setVisibility(View.VISIBLE);
            metaTextViewLabel.setVisibility(View.VISIBLE);
        }
    }

    CharSequence displayContents = resultHandler.getDisplayContents();
    TextView contentsTextView = (TextView) findViewById(R.id.contents_text_view);
    contentsTextView.setText(displayContents);
    int scaledSize = Math.max(22, 32 - displayContents.length() / 4);
    contentsTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, scaledSize);

    TextView supplementTextView = (TextView) findViewById(R.id.contents_supplement_text_view);
    supplementTextView.setText("");
    supplementTextView.setOnClickListener(null);
    if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean(PreferencesActivity.KEY_SUPPLEMENTAL,
            true)) {
        SupplementalInfoRetriever.maybeInvokeRetrieval(supplementTextView, resultHandler.getResult(),
                historyManager, this);
    }

    int buttonCount = resultHandler.getButtonCount();
    ViewGroup buttonView = (ViewGroup) findViewById(R.id.result_button_view);
    buttonView.requestFocus();
    for (int x = 0; x < ResultHandler.MAX_BUTTON_COUNT; x++) {
        TextView button = (TextView) buttonView.getChildAt(x);
        if (x < buttonCount) {
            button.setVisibility(View.VISIBLE);
            button.setText(resultHandler.getButtonText(x));
            button.setOnClickListener(new ResultButtonListener(resultHandler, x));
        } else {
            button.setVisibility(View.GONE);
        }
    }

}