- How to use a RecyclerView to show images from storage
- How to take photos from the camera and gallery on android?
- RUN-Time Permission for Camera and External Storage
- Choose Image from Camera and Gallery
- Handling and Displaying Images in Android
- Using the Image View to Display Images.
- Using the Image Switcher View in Android.
- Downloading and Setting Images on ImageView from Internet.
- Implementing a Gallery Using the Horizontal Scroll View.
- Conclusion
- ImageView
- Общая информация
- Метод setImageResource()
- Метод setImageBitmap()
- Метод setImageDrawable()
- Метод setImageURI()
- Другие методы
- Масштабирование через свойство Scale Type
- Атрибут android:adjustViewBounds=»true»
- Загрузка изображения из галереи
- Получить размеры ImageView — будьте осторожны
- Копирование изображений между ImageView
- Примеры
How to use a RecyclerView to show images from storage
The issue at hand
The RecyclerView widget is a more advanced and flexible version of ListView. It manages and optimizes the view holder bindings according to the scrolling position, and recycles the views so that it uses only a small number of views for a large number of list items. Seeing as the RecyclerView sample app is outdated and doesn’t even compile, this tutorial aims to show a relatively quick way to add a RecyclerView to modern Android Studio projects, and use it to display a list of random images we’ll download to our device.
Creating a new project
Make a new project (or open an existing one). When creating the project, we’ll choose to add a scrolling activity for this example, but you can choose any layout you want.
Run it now for a small sanity check:
Adding a list fragment
Right click on the project folder -> add -> fragment (list) -> finish
This creates a RecyclerView with lots of boilerplate code. Let’s go over the added classes:
MyItemRecyclerViewAdapter — Creates the view holder which, well, holds the views for items in the list and binds the data to the views inside the view holder.
ItemFragment — The fragment that holds and initializes the adapter.
Dummy/DummyContent — Dummy items for populating the list. We’ll replace those with our picture items.
fragment_item_list.xml — contains the RecyclerView widget.
fragment_item.xml — layout of each item in the list.
Now we need to add the fragment we created to our activity. In content_scrolling.xml replace the TextView with:
We’ll also make the activity implement our interaction listener interface:
After adding this to the activity class, you’ll have to implement the onListFragmentInteraction method, you can do it automatically with the suggestion window. This is the auto-generated method that’s added:
Run the project now to see that the list shows and scrolls:
Replacing dummy content
In android studio, rename DummyContent.java to PictureContent.java (and the class name), and move it out of the dummy package. Delete the dummy package. We’ll also delete the DummyItem class, and create a POJO class PictureItem in a new file, containing the picture URI and creation date:
In PictureContent replace the DummyItem creation with a PictureItem creation:
Now we’ll update fragment_item.xml to display our image item with an ImageView for the image and a TextView for the creation date:
Finally, in MyItemRecyclerViewAdapter , replace the content to bind our new data fields to our new views:
Now we’ll populate the list with images saved in the device storage. Add the images loading methods to PictureContent :
We’re going to call loadSavedImages from our activity ScrollingActivity , so we first need to get a reference to the recycler view. Add two fields:
Which will be lazy loaded in onCreate :
And in onResume we’ll add a call to loadSavedImages :
Notice we’re loading the files from DIRECTORY_DOWNLOADS which is a convensional folder for storing downloaded files.
Downloading the pictures
We’ll download random pictures from Lorem Picsum whenever clicking the Floating Action Button, using the built in DownloadManager class.
Add the download method to PictureContent :
This downloads the file to DIRECTORY_DOWNLOADS with the current timestamp as file name.
Set image_download_url in strings.xml :
Don’t forget to add the INTERNET permission to the manifest
Now we need to handle the download complete event. Add the following to activity’s onCreate :
This is the (quite verbose) way of getting the downloaded file name when the download manager completes the download. After getting filePath we call PictureContent.loadImage , which adds it to our list.
Notice the call to recyclerViewAdapter.notifyItemInserted(0) . This will cause the list to refresh with the new item we’ve inserted (at index 0)
Aside: creating a plus icon with Asset Studio
As the final touchup, we’ll update the FAB’s icon, using Android Studio’s Asset Studio, for creating a vector material icon. Right-click the res folder and select New > Vector Asset. Click the Button and search for the keyword add :
This will give us the plus material icon. Change color to white, and save the xml in the drawable folder.
That’s it! Now we have a scrolling RecyclerView showing the downloaded pictures:
Источник
How to take photos from the camera and gallery on android?
With respect to an Android novice, to test things out, you would require a straightforward and clear guide. As you can discover, there are numerous articles, sites, and aides on this subject. However, a large portion of them is not working as well as haven’t tried or too complex to even think about understanding. Let me take you through a guide on the most proficient method to execute this without any problem.
you can download the full source code from Github.
First, you must have a ImageView in your layout implemented to capture the image you upload either through the camera or Gallery.
Following is my ImageView implementation for the above purpose.
Now, after doing this your activity_main.xml will look like this.
Now in the MainActivity class, you have to declare the ImageView first.
In the onCreate override method, you have to initialize the ImageView element by adding the following,
RUN-Time Permission for Camera and External Storage
as you aware that if you are working with marshmallow or above version device then you need to take first run time permission. for our app, we will require two run time permission.
- Camera Permission
- External Storage Permission
So let’s see how you will get this permission
first you need to define this two permission in your manifest file ie. AndroidManifest.xml
Now, your AndroidManifest.xml will look like this:
Okay after adding this two permission on the manifest file you need to make a function to check runtime permission on MainActivity. This function will show a popup if the user doesn’t have permission so that the user can click on the allow button to grant permission to your APP.
Now you need to Override onRequestPermissionsResult where you will handle your permission result. if permission granted then you can proceed to call chooseImage function.
Choose Image from Camera and Gallery
Now let’s see chooseImage function, which will show a dialog with three option
- Take Photo
- choose a photo from the gallery
- Exit
Now to handle the result of your startActivityForResult, you need to override onActivityResult
Once you are done with all of the steps, then you call the permission check function in the onCreate method.
So after doing all of the things your MainActivity.java will look like this
That’s it, now you can run your app and enjoy the code.
I hope you enjoy this tutorial and you have learned how to get images from the gallery or capture images from the camera on Android.
Источник
Handling and Displaying Images in Android
Android provides many views which we can use to define a user interface for our apps. Amongst these it provides a large number to display information and take input from the user, these include text and image views.
Android provides views which can be used to display images from various sources and provide transitions between them. Some of these views are the ImageView and the ImageSwitcher . These views provide a high level of functionality to display images in a user interface so that we can concentrate on the images we want to display rather than taking care of rendering.
In this article we are going to see how we can use these views effectively in a user interface.
Using the Image View to Display Images.
To render images Android provides us with the ImageView class. Let’s start by creating a program that will use an ImageView to display some images and a button which when clicked will change the image in the ImageView . You can find the code for this section on GitHub.
Create a basic Android project with an Activity that sets the main view from a layout file and does nothing else. Then open the layout file and add the ImageView and a button as shown below:
In the code above we created a LinearLayout and added an ImageView to display an image and a button which will rotate the images in the imageView .
Add some images to the resource folder depending on the screen sizes you are planning to support as shown below:
Now update your Activity code as follows, using appropriate names for your project:
Above we created an Array of the resource IDs for the images stored in our resources folder. In the OnCreate method we set the content view to the layout created. In the setImageRotateListener function we set up a listener to the onClick event of the button which changes the currentImage counter and sets the new image in the ImageView .
The setCurrentImage function gets the ImageView object using the findViewById function, then sets the resource id of the current image using the setImageResource function on the ImageView which will display the image in the image view.
If you run the program you should see the image in the image view and clicking it should change the image to the next one:
Using the Image Switcher View in Android.
In the above example we switched the image in the image view. This switching of images does not happen in a very smooth way and you might want to use a transition when the image changes. For this we use the ImageSwitcher View.
First add an image switcher view to the layout as follows:
Then add the following code to our Activity which will initialise the ImageSwitcher and setup the button to change the image with a transition.
In the code above we get the ImageSwitcher object and then set the ViewFactory which creates a plain ImageView . Then we set the animation to fade in and fade out. We update the setCurrentImage function to set the images in the ImageSwitcher.
Now the image will change with an animation.
Downloading and Setting Images on ImageView from Internet.
You might not always have images available to you locally and may instead want to display them from the internet.
You should not undertake any network operations in the UI thread, instead the download should happen in a different background thread. We will do this in an Async Task. First set the permission to use the Internet in our AndroidManifest.xml as follows:
The layout of your project should have one ImageView and a Button as shown:
Then we create an AsyncTask which takes the ImageView and URL to download, downloads the image and sets the image in the ImageView .
The ImageDownloader async task downloads the image data and sets the ImageView . The complete activity code should now be as follows:
In the above code we stored the URLs of the images in the imageUrls array. In the setCurrentImage function we pass the ImageView to the ImageDownloader Async task and pass the URL of the image to download and set in the ImageView . The ImageDownloader Async task will download the image and set it in the ImageView .
Implementing a Gallery Using the Horizontal Scroll View.
In the above examples we saw how to display one image at a time using an ImageView . Sometimes we might want to display a variable number of images and let the user scroll through them. This we can achieve by putting a LinearLayout inside a horizontal scrollView and then dynamically add ImageViews to that linear layout. For this we create a new activity called ImageGalleryActivity and update the layout file accordingly:
And code of the Activity:
In the code above we dynamically create the ImageViews and add margins to them. The LinerLayout has the orientation set to horizontal. Now if we run the program, we will be able to see the images in a Horizontally scrollable gallery as seen below.
Conclusion
Images are a big part of modern mobile interfaces and hopefully this tutorial has shown you some of the tools Android provides to make this easy. What are you waiting for? Get visual!
Источник
ImageView
Общая информация
Компонент ImageView предназначен для отображения изображений. Находится в разделе Widgets.
Для загрузки изображения в XML-файле используется атрибут android:src, в последнее время чаще используется атрибут app:srcCompat.
ImageView является базовым элементом-контейнером для использования графики. Можно загружать изображения из разных источников, например, из ресурсов программы, контент-провайдеров. В классе ImageView существует несколько методов для загрузки изображений:
- setImageResource(int resId) — загружает изображение по идентификатору ресурса
- setImageBitmap(Bitmap bitmap) — загружает растровое изображение
- setImageDrawable(Drawable drawable) — загружает готовое изображение
- setImageURI(Uri uri) — загружает изображение по его URI
Метод setImageResource()
Сначала нужно получить ссылку на ImageView, а затем используется идентификатор изображения из ресурсов:
Метод setImageBitmap()
Используется класс BitmapFactory для чтения ресурса изображения в объект Bitmap, а затем в ImageView указывается полученный Bitmap. Могут быть и другие варианты.
Метод setImageDrawable()
Если у вас есть готовое изображение, например, на SD-карте, то его можно использовать в качестве объекта Drawable.
Drawable можно получить и из ресурсов, хотя такой код выглядит избыточным, если можно сразу вызвать setImageResource().
Метод setImageURI()
Берётся URI файла изображения и используется в качестве источника изображения. Этот способ годится для работы с локальными изображениями.
Загружаем Drawable через URI.
Другие методы
Также вам часто придется использовать методы, связанные с размерами и масштабированием: setMaxHeight(), setMaxWidth(), getMinimunHeight(), getMinimunWidth(), getScaleType(), setScaleType().
Масштабирование через свойство Scale Type
Для масштабирования картинки в ImageView есть свойство Scale Type и соответствующий ему атрибут android:scaleType и перечисление ImageView.ScaleType.
- CENTER
- CENTER_CROP
- CENTER_INSIDE
- FIT_CENTER
- FIT_START
- FIT_END
- FIT_XY
- MATRIX
Чтобы увидеть разницу между разными режимами, желательно использовать большую картинку, превосходящую по ширине экрана устройства. Допустим, у нас есть простенькая разметка:
Для наглядности я задал красный цвет для фона ImageView.
Режим android:scaleType=»center» выводит картинку в центре без масштабирования. Если у вас будет картинка большего размера, то края могут быть обрезаны.
Режим android:scaleType=»centerCrop» также размещает картинку в центре, но учитывает ширину или высоту контейнера. Режим попытается сделать так, чтобы ширина (или высота) картинки совпала с шириной (или высотой) контейнера, а остальное обрезается.
Режим android:scaleType=»centerInside» масштабирует картинку, сохраняя пропорции. Можно увидеть задний фон контейнера, если его размеры отличаются от размера картинки.
Режим android:scaleType=»fitCenter» (по умолчанию) похож на предыдущий, но может не сохранять пропорции.
Если выбрать режим android:scaleType=»fitStart», то картинка прижимается к левому верхнему углу и таким образом заполняет верхнюю половину контейнера.
Значение android:scaleType=»fitEnd» сместит картинку в нижнюю часть контейнера.
Режим android:scaleType=»fitXY» растягивает/сжимает картинку, чтобы подогнать её к контейнеру. Может получиться вытянутая картинка, поэтому будьте осторожны.
Последний атрибут android:scaleType=»matrix» вывел картинку без изменений в левом верхнем углу с обрезанными краями.
Атрибут android:adjustViewBounds=»true»
При использовании атрибута scaleType=»fitCenter» из предыдущего примера Android вычисляет размеры самой картинки, игнорируя размеры ImageView. В этом случае ваша разметка может «поехать». Атрибут adjustViewBounds заставляет картинку подчиниться размеру компонента-контейнера. В некоторых случаях это может не сработать, например, если у ImageView установлен атрибут layout_width=»0dip». В таком случае поместите ImageView в RelativeLayout или FrameLayout и используйте значение 0dip для этих контейнеров.
Загрузка изображения из галереи
Предположим, у вас есть на экране компонент ImageView, и вы хотите загрузить в него какое-нибудь изображение из галереи по нажатию кнопки:
Намерение ACTION_PICK вызывает отображение галереи всех изображений, хранящихся на телефоне, позволяя выбрать одно изображение. При этом возвращается адрес URI, определяющий местоположение выбранного изображения. Для его получения используется метод getData(). Далее для преобразования URI-адреса в соответствующий экземпляр класса Bitmap используется специальный метод Media.getBitmap(). И у нас появляется возможность установить изображение в ImageView при помощи setImageBitmap().
На самом деле можно поступить ещё проще и использовать метод setImageURI.
Сравните с предыдущим примером — чувствуете разницу? Тем не менее, приходится часто наблюдать подобный избыточный код во многих проектах. Это связано с тем, что метод порой кэширует адрес и не происходит изменений. Рекомендуется использовать инструкцию setImageURI(null) для сброса кэша и повторный вызов метода с нужным Uri.
В последних версиях системных эмуляторов два примера не работают. Проверяйте на реальных устройствах.
Получить размеры ImageView — будьте осторожны
У элемента ImageView есть два метода getWidth() и getHeight(), позволяющие получить его ширину и высоту. Но если вы попробуете вызвать указанные методы сразу в методе onCreate(), то они возвратят нулевые значения. Можно добавить кнопку и вызвать данные методы через нажатие, тогда будут получены правильные результаты. Либо использовать другой метод активности, который наступает позже.
Копирование изображений между ImageView
Если вам надо скопировать изображение из одного ImageView в другой, то можно получить объект Drawable через метод getDrawable() и присвоить ему второму компоненту.
Примеры
В моих статьях можно найти примеры использования ImageView.
Источник