Example usage for android.widget ImageView setImageURI

List of usage examples for android.widget ImageView setImageURI

Introduction

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

Prototype

@android.view.RemotableViewMethod(asyncImpl = "setImageURIAsync")
public void setImageURI(@Nullable Uri uri) 

Source Link

Document

Sets the content of this ImageView to the specified Uri.

Usage

From source file:br.com.brolam.cloudvision.ui.helpers.ImagesHelper.java

/**
 * Realizar a solicitao do download ou recuperar a imagem do arquivo temporrio e exibir
 * em um ImageView para uma imagem de background Note Vision
 * @param noteVisionKey informar uma chave vlida.
 * @param noteVision informar um Note Vision vlido.
 * @param imageView informar um ImageView vlido.
 *///from w ww.  j av a 2 s .c  o m
public void loadNoteVisionBackground(String noteVisionKey, HashMap noteVision, ImageView imageView) {
    //Endereo da imagem no Firebase Storage.
    String pathNoteVisionBackground = NoteVision.getBackgroundPath(this.cloudVisionProvider.getUserId(),
            noteVisionKey);
    imageView.setImageBitmap(null);
    NoteVision.BackgroundOrigin backgroundOrigin = NoteVision.getBackground(noteVision);

    if (backgroundOrigin == NoteVision.BackgroundOrigin.LOCAL) {
        /**
         * Se o upload da imagem de background ainda no foi realizado, ser exibida
         * a imagem do arquivo temporrio.
         */
        imageView.setImageURI(getImageUriFile(noteVisionKey));
        //Relizar uma requisio de upload se ainda no existir uma requisio ativia.
        requestNoteVisionBackgroundPutFile(noteVisionKey);

    } else if (backgroundOrigin == NoteVision.BackgroundOrigin.REMOTE) {
        Glide.with(this.activity).using(new FirebaseImageLoader())
                .load(this.firebaseStorage.getReference(pathNoteVisionBackground))
                .diskCacheStrategy(DiskCacheStrategy.RESULT)
                //Quando uma imagem  atualizado, uma nova assinatura deve ser criada
                //para o Glide tambm atualizar a imagem em cache.
                .signature(new StringSignature(NoteVision.getBackgroundSignature(noteVision))).into(imageView);
    }
}

From source file:ru.tlrs.vincent.LightBox.java

@Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    Log.d(TAG, "onCreateView: ");
    inflateView(inflater, container);//from   www .  j a  v a 2 s . c  o m
    final ImageView fullImage = (ImageView) view.findViewById(R.id.fullImage);
    fullImage.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
        @Override
        public boolean onPreDraw() {
            fullImage.getViewTreeObserver().removeOnPreDrawListener(this);
            int height = fullImage.getMeasuredHeight();
            int width = fullImage.getMeasuredWidth();
            Log.d(TAG, "onPreDraw: " + String.format("height: %s, width: %s", height, width));
            //Rect view = new Rect(0,0,width, height);
            Drawable drawable = ((ImageView) getActivity().findViewById(parentId)).getDrawable();
            /*drawable = drawable.mutate();
            //Rect draw = drawable.getBounds();
            int h = drawable.getIntrinsicHeight();
            int w = drawable.getIntrinsicWidth();
            //drawable.setBounds(0,0,w,h);
            drawable.setBounds(new Rect(0,0,width,height));
            //ScaleDrawable sd = new ScaleDrawable(drawable, 0, 1.0f ,1.0f );*/
            //fullImage.setImageDrawable(drawable);
            //fullImage.setImageURI(null);
            Log.d(TAG, "onPreDraw: mSrc = " + mSrc);
            fullImage.setImageURI(Uri.parse("android.resource://com.example.vincent/" + mSrc)); //give "More than two path segments", instead of NullPointer
            return false;
        }
    });

    //((ImageView) view.findViewById(R.id.fullImage)).setImageDrawable(((ImageView) getActivity().findViewById(parentId)).getDrawable());
    ((TextView) view.findViewById(R.id.description)).setText(mDesc);
    return view;
}

From source file:im.vector.activity.SettingsActivity.java

@Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == REQUEST_IMAGE) {
        if (resultCode == RESULT_OK) {

            this.runOnUiThread(new Runnable() {
                @Override//from  www.j  av a 2 s . c om
                public void run() {
                    final LinearLayout linearLayout = mLinearLayoutBySession.get(mUpdatingSession);
                    ImageView avatarView = (ImageView) linearLayout.findViewById(R.id.imageView_avatar);

                    Uri imageUri = data.getData();
                    Bitmap thumbnailBitmap = null;
                    Uri scaledImageUri = data.getData();

                    try {
                        ResourceUtils.Resource resource = ResourceUtils.openResource(SettingsActivity.this,
                                imageUri);

                        // with jpg files
                        // check exif parameter and reduce image size
                        if ("image/jpg".equals(resource.mimeType) || "image/jpeg".equals(resource.mimeType)) {
                            InputStream stream = resource.contentStream;
                            int rotationAngle = ImageUtils.getRotationAngleForBitmap(SettingsActivity.this,
                                    imageUri);

                            String mediaUrl = ImageUtils.scaleAndRotateImage(SettingsActivity.this, stream,
                                    resource.mimeType, 1024, rotationAngle, SettingsActivity.this.mMediasCache);
                            scaledImageUri = Uri.parse(mediaUrl);
                        } else {
                            ContentResolver resolver = getContentResolver();

                            List uriPath = imageUri.getPathSegments();
                            long imageId = -1;
                            String lastSegment = (String) uriPath.get(uriPath.size() - 1);

                            // > Kitkat
                            if (lastSegment.startsWith("image:")) {
                                lastSegment = lastSegment.substring("image:".length());
                            }

                            imageId = Long.parseLong(lastSegment);
                            thumbnailBitmap = MediaStore.Images.Thumbnails.getThumbnail(resolver, imageId,
                                    MediaStore.Images.Thumbnails.MINI_KIND, null);
                        }

                        resource.contentStream.close();

                    } catch (Exception e) {
                        Log.e(LOG_TAG, "MediaStore.Images.Thumbnails.getThumbnail " + e.getMessage());
                    }

                    if (null != thumbnailBitmap) {
                        avatarView.setImageBitmap(thumbnailBitmap);
                    } else {
                        avatarView.setImageURI(scaledImageUri);
                    }

                    mTmpThumbnailUriBySession.put(mUpdatingSession, scaledImageUri);

                    final Button saveButton = (Button) linearLayout.findViewById(R.id.button_save);
                    saveButton.setEnabled(true); // Enable the save button if it wasn't already
                }
            });
        }

        mUpdatingSession = null;
    }
}

From source file:org.matrix.console.activity.SettingsActivity.java

@Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == REQUEST_IMAGE) {
        if (resultCode == RESULT_OK) {

            this.runOnUiThread(new Runnable() {
                @Override/*from w  w  w  .  ja v a 2  s. c o m*/
                public void run() {
                    final LinearLayout linearLayout = mLinearLayoutByMatrixId.get(mUpdatingSessionId);

                    // sanity checks
                    if (null != linearLayout) {
                        ImageView avatarView = (ImageView) linearLayout.findViewById(R.id.imageView_avatar);

                        Uri imageUri = data.getData();
                        Bitmap thumbnailBitmap = null;
                        Uri scaledImageUri = data.getData();

                        try {
                            ResourceUtils.Resource resource = ResourceUtils.openResource(SettingsActivity.this,
                                    imageUri);

                            // with jpg files
                            // check exif parameter and reduce image size
                            if ("image/jpg".equals(resource.mimeType)
                                    || "image/jpeg".equals(resource.mimeType)) {
                                InputStream stream = resource.contentStream;
                                int rotationAngle = ImageUtils.getRotationAngleForBitmap(SettingsActivity.this,
                                        imageUri);

                                String mediaUrl = ImageUtils.scaleAndRotateImage(SettingsActivity.this, stream,
                                        resource.mimeType, 1024, rotationAngle,
                                        SettingsActivity.this.mMediasCache);
                                scaledImageUri = Uri.parse(mediaUrl);
                            } else {
                                ContentResolver resolver = getContentResolver();

                                List uriPath = imageUri.getPathSegments();
                                long imageId = -1;
                                String lastSegment = (String) uriPath.get(uriPath.size() - 1);

                                // > Kitkat
                                if (lastSegment.startsWith("image:")) {
                                    lastSegment = lastSegment.substring("image:".length());
                                }

                                imageId = Long.parseLong(lastSegment);
                                thumbnailBitmap = MediaStore.Images.Thumbnails.getThumbnail(resolver, imageId,
                                        MediaStore.Images.Thumbnails.MINI_KIND, null);
                            }

                            resource.contentStream.close();

                        } catch (Exception e) {
                            Log.e(LOG_TAG, "MediaStore.Images.Thumbnails.getThumbnail " + e.getMessage());
                        }

                        if (null != thumbnailBitmap) {
                            avatarView.setImageBitmap(thumbnailBitmap);
                        } else {
                            avatarView.setImageURI(scaledImageUri);
                        }

                        mTmpThumbnailUriByMatrixId.put(mUpdatingSessionId, scaledImageUri);

                        final Button saveButton = (Button) linearLayout.findViewById(R.id.button_save);
                        saveButton.setEnabled(true); // Enable the save button if it wasn't already
                    }
                }
            });
        }

        mUpdatingSessionId = null;
    }
}

From source file:org.telegram.ui.ChatActivity.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    if (fragmentView == null) {
        fragmentView = inflater.inflate(R.layout.chat_layout, container, false);

        sizeNotifierRelativeLayout = (SizeNotifierRelativeLayout) fragmentView.findViewById(R.id.chat_layout);
        sizeNotifierRelativeLayout.delegate = this;
        contentView = sizeNotifierRelativeLayout;

        emptyView = (TextView) fragmentView.findViewById(R.id.searchEmptyView);
        chatListView = (LayoutListView) fragmentView.findViewById(R.id.chat_list_view);
        chatListView.setAdapter(chatAdapter = new ChatAdapter(parentActivity));
        topPanel = fragmentView.findViewById(R.id.top_panel);
        topPlaneClose = (ImageView) fragmentView.findViewById(R.id.top_plane_close);
        topPanelText = (TextView) fragmentView.findViewById(R.id.top_panel_text);
        bottomOverlay = fragmentView.findViewById(R.id.bottom_overlay);
        bottomOverlayText = (TextView) fragmentView.findViewById(R.id.bottom_overlay_text);
        View bottomOverlayChat = fragmentView.findViewById(R.id.bottom_overlay_chat);
        progressView = fragmentView.findViewById(R.id.progressLayout);
        pagedownButton = fragmentView.findViewById(R.id.pagedown_button);
        audioSendButton = (ImageButton) fragmentView.findViewById(R.id.chat_audio_send_button);
        View progressViewInner = progressView.findViewById(R.id.progressLayoutInner);

        updateContactStatus();/*from  w w w. j a v a2  s .  c o  m*/

        ImageView backgroundImage = (ImageView) fragmentView.findViewById(R.id.background_image);

        SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig",
                Activity.MODE_PRIVATE);
        int selectedBackground = preferences.getInt("selectedBackground", 1000001);
        int selectedColor = preferences.getInt("selectedColor", 0);
        if (selectedColor != 0) {
            backgroundImage.setBackgroundColor(selectedColor);
            chatListView.setCacheColorHint(selectedColor);
        } else {
            chatListView.setCacheColorHint(0);
            if (selectedBackground == 1000001) {
                backgroundImage.setImageResource(R.drawable.background_hd);
            } else {
                File toFile = new File(ApplicationLoader.applicationContext.getFilesDir(), "wallpaper.jpg");
                if (toFile.exists()) {
                    if (ApplicationLoader.cachedWallpaper != null) {
                        backgroundImage.setImageBitmap(ApplicationLoader.cachedWallpaper);
                    } else {
                        backgroundImage.setImageURI(Uri.fromFile(toFile));
                        if (backgroundImage.getDrawable() instanceof BitmapDrawable) {
                            ApplicationLoader.cachedWallpaper = ((BitmapDrawable) backgroundImage.getDrawable())
                                    .getBitmap();
                        }
                    }
                    isCustomTheme = true;
                } else {
                    backgroundImage.setImageResource(R.drawable.background_hd);
                }
            }
        }

        if (currentEncryptedChat != null) {
            secretChatPlaceholder = contentView.findViewById(R.id.secret_placeholder);
            if (isCustomTheme) {
                secretChatPlaceholder.setBackgroundResource(R.drawable.system_black);
            } else {
                secretChatPlaceholder.setBackgroundResource(R.drawable.system_blue);
            }
            secretViewStatusTextView = (TextView) contentView.findViewById(R.id.invite_text);
            secretChatPlaceholder.setPadding(Utilities.dp(16), Utilities.dp(12), Utilities.dp(16),
                    Utilities.dp(12));

            View v = contentView.findViewById(R.id.secret_placeholder);
            v.setVisibility(View.VISIBLE);

            if (currentEncryptedChat.admin_id == UserConfig.clientUserId) {
                if (currentUser.first_name.length() > 0) {
                    secretViewStatusTextView
                            .setText(String.format(getStringEntry(R.string.EncryptedPlaceholderTitleOutgoing),
                                    currentUser.first_name));
                } else {
                    secretViewStatusTextView.setText(String.format(
                            getStringEntry(R.string.EncryptedPlaceholderTitleOutgoing), currentUser.last_name));
                }
            } else {
                if (currentUser.first_name.length() > 0) {
                    secretViewStatusTextView
                            .setText(String.format(getStringEntry(R.string.EncryptedPlaceholderTitleIncoming),
                                    currentUser.first_name));
                } else {
                    secretViewStatusTextView.setText(String.format(
                            getStringEntry(R.string.EncryptedPlaceholderTitleIncoming), currentUser.last_name));
                }
            }

            updateSecretStatus();
        }

        if (isCustomTheme) {
            progressViewInner.setBackgroundResource(R.drawable.system_loader2);
            emptyView.setBackgroundResource(R.drawable.system_black);
        } else {
            progressViewInner.setBackgroundResource(R.drawable.system_loader1);
            emptyView.setBackgroundResource(R.drawable.system_blue);
        }
        emptyView.setPadding(Utilities.dp(7), Utilities.dp(1), Utilities.dp(7), Utilities.dp(1));

        if (currentUser != null && currentUser.id == 333000) {
            emptyView.setText(R.string.GotAQuestion);
        }

        chatListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapter, View view, int position, long id) {
                if (mActionMode == null) {
                    createMenu(view, false);
                }
                return true;
            }
        });

        chatListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int i) {

            }

            @Override
            public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount,
                    int totalItemCount) {
                if (visibleItemCount > 0) {
                    if (firstVisibleItem <= 4) {
                        if (!endReached && !loading) {
                            if (messagesByDays.size() != 0) {
                                MessagesController.Instance.loadMessages(dialog_id, 0, 20, maxMessageId,
                                        !cacheEndReaced, minDate, classGuid, false, false);
                            } else {
                                MessagesController.Instance.loadMessages(dialog_id, 0, 20, 0, !cacheEndReaced,
                                        minDate, classGuid, false, false);
                            }
                            loading = true;
                        }
                    }
                    if (firstVisibleItem + visibleItemCount >= totalItemCount - 6) {
                        if (!unread_end_reached && !loadingForward) {
                            MessagesController.Instance.loadMessages(dialog_id, 0, 20, minMessageId, true,
                                    maxDate, classGuid, false, true);
                            loadingForward = true;
                        }
                    }
                    if (firstVisibleItem + visibleItemCount == totalItemCount && unread_end_reached) {
                        showPagedownButton(false, true);
                    }
                } else {
                    showPagedownButton(false, false);
                }
            }
        });

        messsageEditText = (EditText) fragmentView.findViewById(R.id.chat_text_edit);

        sendButton = (ImageButton) fragmentView.findViewById(R.id.chat_send_button);
        sendButton.setEnabled(false);
        sendButton.setVisibility(View.INVISIBLE);
        emojiButton = (ImageView) fragmentView.findViewById(R.id.chat_smile_button);

        if (loading && messages.isEmpty()) {
            progressView.setVisibility(View.VISIBLE);
            chatListView.setEmptyView(null);
        } else {
            progressView.setVisibility(View.GONE);
            if (currentEncryptedChat == null) {
                chatListView.setEmptyView(emptyView);
            } else {
                chatListView.setEmptyView(secretChatPlaceholder);
            }
        }

        emojiButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (emojiPopup == null) {
                    showEmojiPopup(true);
                } else {
                    showEmojiPopup(!emojiPopup.isShowing());
                }
            }
        });

        messsageEditText.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View view, int i, KeyEvent keyEvent) {
                if (i == 4 && !keyboardVisible && emojiPopup != null && emojiPopup.isShowing()) {
                    if (keyEvent.getAction() == 1) {
                        showEmojiPopup(false);
                    }
                    return true;
                } else if (i == KeyEvent.KEYCODE_ENTER && sendByEnter
                        && keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
                    sendMessage();
                    return true;
                }
                return false;
            }
        });

        messsageEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                if (i == EditorInfo.IME_ACTION_SEND) {
                    sendMessage();
                    return true;
                } else if (sendByEnter) {
                    if (keyEvent != null && i == EditorInfo.IME_NULL
                            && keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
                        sendMessage();
                        return true;
                    }
                }
                return false;
            }
        });

        sendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sendMessage();
            }
        });

        audioSendButton.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                    startRecording();
                } else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                    stopRecording();
                }
                return false;
            }
        });

        pagedownButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (unread_end_reached || first_unread_id == 0) {
                    chatListView.setSelectionFromTop(messages.size() - 1,
                            -10000 - chatListView.getPaddingTop());
                } else {
                    messages.clear();
                    messagesByDays.clear();
                    messagesDict.clear();
                    progressView.setVisibility(View.VISIBLE);
                    chatListView.setEmptyView(null);
                    maxMessageId = Integer.MAX_VALUE;
                    minMessageId = Integer.MIN_VALUE;
                    maxDate = Integer.MIN_VALUE;
                    minDate = 0;
                    MessagesController.Instance.loadMessages(dialog_id, 0, 30, 0, true, 0, classGuid, true,
                            false);
                    loading = true;
                    chatAdapter.notifyDataSetChanged();
                }
            }
        });

        checkSendButton();

        messsageEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
                String message = charSequence.toString().trim();
                message = message.replaceAll("\n\n+", "\n\n");
                message = message.replaceAll(" +", " ");
                sendButton.setEnabled(message.length() != 0);
                checkSendButton();

                if (message.length() != 0 && lastTypingTimeSend < System.currentTimeMillis() - 5000
                        && !ignoreTextChange) {
                    int currentTime = ConnectionsManager.Instance.getCurrentTime();
                    if (currentUser != null && currentUser.status != null
                            && currentUser.status.expires < currentTime
                            && currentUser.status.was_online < currentTime) {
                        return;
                    }
                    lastTypingTimeSend = System.currentTimeMillis();
                    MessagesController.Instance.sendTyping(dialog_id, classGuid);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (sendByEnter && editable.length() > 0 && editable.charAt(editable.length() - 1) == '\n') {
                    sendMessage();
                }
                int i = 0;
                ImageSpan[] arrayOfImageSpan = editable.getSpans(0, editable.length(), ImageSpan.class);
                int j = arrayOfImageSpan.length;
                while (true) {
                    if (i >= j) {
                        Emoji.replaceEmoji(editable);
                        return;
                    }
                    editable.removeSpan(arrayOfImageSpan[i]);
                    i++;
                }
            }
        });

        bottomOverlayChat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (currentChat != null) {
                    MessagesController.Instance.deleteDialog(-currentChat.id, 0, false);
                    finishFragment();
                }
            }
        });

        chatListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (mActionMode != null) {
                    processRowSelect(view);
                    return;
                }
                if (!spanClicked(chatListView, view, R.id.chat_message_text)) {
                    createMenu(view, true);
                }
            }
        });

        chatListView.setOnTouchListener(new OnSwipeTouchListener() {
            public void onSwipeRight() {
                try {
                    if (visibleDialog != null) {
                        visibleDialog.dismiss();
                        visibleDialog = null;
                    }
                } catch (Exception e) {
                    FileLog.e("tmessages", e);
                }
                finishFragment(true);
            }

            public void onSwipeLeft() {
                if (swipeOpening) {
                    return;
                }
                try {
                    if (visibleDialog != null) {
                        visibleDialog.dismiss();
                        visibleDialog = null;
                    }
                } catch (Exception e) {
                    FileLog.e("tmessages", e);
                }
                if (avatarImageView != null) {
                    swipeOpening = true;
                    avatarImageView.performClick();
                }
            }

            @Override
            public void onTouchUp(MotionEvent event) {
                mLastTouch.right = (int) event.getX();
                mLastTouch.bottom = (int) event.getY();
            }
        });

        emptyView.setOnTouchListener(new OnSwipeTouchListener() {
            public void onSwipeRight() {
                finishFragment(true);
            }

            public void onSwipeLeft() {
                if (swipeOpening) {
                    return;
                }
                if (avatarImageView != null) {
                    swipeOpening = true;
                    avatarImageView.performClick();
                }
            }
        });
        if (currentChat != null && (currentChat instanceof TLRPC.TL_chatForbidden || currentChat.left)) {
            bottomOverlayChat.setVisibility(View.VISIBLE);
        } else {
            bottomOverlayChat.setVisibility(View.GONE);
        }
    } else {
        ViewGroup parent = (ViewGroup) fragmentView.getParent();
        if (parent != null) {
            parent.removeView(fragmentView);
        }
    }
    return fragmentView;
}