- GridView
- Знакомьтесь — GridView
- Свойства
- Базовый пример
- GridView с картинками
- GridView с картинками и пояснительным текстом
- res/layout/cellgrid.xml
- Убрать вертикальную прокрутку
- Галерея
- Загружаем картинки из внешнего накопителя
- ImageAdapter.java
- GridView кастомный адаптер
- Шаг 1. Создание проекта
- Шаг 2. Объект – элемент GridView
- Шаг 3. Создаём адаптер
- Шаг 4. Применяем наш адаптер
- More Kotlin Android Tutorial
- Kotlin GridView
- Tutorialwing
- Output
- Getting Started
- Creating New Project
- Setup ViewBinding
- Using GridView in Kotlin
- Create View For Single Item in GridView
- Create Adapter For GridView
- Custom Adapter Using BaseAdapter
- Difference between BaseAdapter and ArrayAdapter
- Different Attributes of GridView in XML
- Set Id of GridView
- Set Width of GridView
- Set Height of GridView
- Set Padding of GridView
- Set Margin of GridView
- Set Background of GridView
- Set Visibility of GridView
GridView
Знакомьтесь — GridView
Компонент GridView представляет собой плоскую таблицу. Для GridView можно использовать собственные поля для отображения элементов данных, создав класс, производный от класса ArrayAdapter или BaseAdapter и т.п, и переопределив его метод getView().
В старых версиях студии находился в разделе Containers, сейчас находится в Legacy и считается устаревшим.
Число столбцов для GridView чаще задаётся статически. Число строк в элементе определяется динамически на основании числа элементов, которые предоставляет адаптер.
Свойства
- android:numColumns — определяет количество столбцов. Если поставлено значение auto_fit, то система вычислит количество столбцов, основанное на доступном пространстве
- android:verticalSpacing — устанавливает размер пустого пространства между ячейками таблицы
- android:columnWidth — устанавливает ширину столбцов
- android:stretchMode — указывает, куда распределяется остаток свободного пространства для таблицы с установленным значением android:numColumns=»auto_fit». Принимает значения columnWidth для paспределения остатка свободного пространства между ячейками столбцов для их увеличения или spacingWidth — для увеличения пространства между ячейками
Базовый пример
Если поместить GridView на форму, то увидим следующую картину.
Внесём небольшие правки
В коде реализуем наполнение таблицы через адаптер. Создадим новый файл DataAdapter.java:
Теперь напишем код для основного окна приложения. Как и у ListView, нам нужно использовать метод setAdapter(), а также методы setOnItemSelectedListener(), onItemSelected(), onNothingSelected().
Запустите проект и начинайте выбирать любой элемент — его название отобразится в текстовой метке в верхней части экрана. Я обратил внимание, что в эмуляторе с помощью джойстика можно выбрать нужный элемент, но в современных телефонах джойстика нет, поэтому я позже добавил метод setOnItemClickListener(), чтобы можно было щёлкать по элементам в GridView и выводить их названия в метке.
GridView с картинками
Вместо текста можно использовать и картинки. Немного модифицируем проект. В шаблоне разметки изменим GridView:
Создадим новый адаптер ImageAdapter.java, в котором будет возможность подключать картинки
Теперь код в основной активности:
Зная номер позиции можно доработать программу, чтобы при щелчке на картинке, она открывалась на весь экран. Давайте так и сделаем. Создадим новый XML-файл разметки в папке res/layout под именем full_image.xml:
Создадим новую активность, в которой будет выводиться изображение на весь экран (файл FullImageActivity.java):
Класс получает от намерения номер позиции и выводит по этому номеру изображение из ресурсов.
Теперь в основной активности модифицируем код для щелчка
Осталось добавить в манифест новую активность:
У нас получилась галерея с просмотром отдельной картинки.
GridView с картинками и пояснительным текстом
Модифицируем предыдущий пример и создадим сетку, состоящую из картинок с сопроводительным текстом внизу.
Можно было оставить предыдущую разметку для активности, но я решил чуть её изменить, убрав лишние элементы
Теперь создадим разметку для отдельной ячейки сетки — нам нужны ImageView и TextView:
res/layout/cellgrid.xml
Создадим новый класс ImageTextAdapter. Он практически не отличается от класса ImageAdapter, поменялся только метод getView(), разницу в коде я закоментировал для сравнения
Осталось вызвать нужный адаптер в активности:
Убрать вертикальную прокрутку
Прочитал заметку про убирание вертикальной прокрутки, которая возникает при движении пальцем вверх. Может пригодится кому-то:
Галерея
Рассмотрим вариант создания галереи на основе GridView.
Создаём новый проект. Также нужно подготовить фотографии для галереи, которые следует поместить в папку res/drawable-hdpi.
Поместим на главном экране приложения GridView:
Создадим новый класс ImageAdapter.java, наследующий от BaseAdapter, для размещения изображений в сетке GridView через собственный адаптер.
Открываем основной класс приложения и связываем через созданный адаптер изображения с GridView:
Запустим проект и проверим, что всё отображается нормально.
Не обращайте внимания, что картинки на скриншоте повторяются, просто было лень готовить пятнадцать разных фотографий.
На этом урок можно было закончить, но давайте доработаем приложение, чтобы выбранная картинка отображалась в полном размере на весь экран. Для этого нужно передать идентификатор выбранного изображения новой активности.
Создадим в папке layout файл разметки full_image.xml для этой цели.
Создадим новый класс FullImageActivity.java для активности, которая будет отображать картинку на весь экран. Активность через намерение будет получать идентификатор картинки и выводить её на экран.
Не забываем прописать новый класс в манифесте проекта.
Возвращаемся к главной активности и добавляем обработчик щелчков на сетке:
Снова запускаем проект и щёлкаем по любой миниатюре — должен запуститься новый экран с картинкой во весь рост. Теперь можно разглядеть кота получше.
Загружаем картинки из внешнего накопителя
Попробуем загрузить картинки с внешнего накопителя в GridView. Пример писался под Android 2.3, возможно сейчас уже не заработает.
Разметка основного экрана состоит из одного компонента GridView:
Для данного компонента нужен адаптер. Создадим новый класс ImageAdapter.
ImageAdapter.java
Код для главной активности:
В этом примере при щелчке выводится всплывающее сообщение. Вы можете запустить новую активность с показом выбранной картинки.
Источник
GridView кастомный адаптер
Чаще всего используя GridView вам придётся писать свой кастомный адаптер, например хотя бы для того чтобы заполнять свой GridView списком объектов, именно это мы и рассмотрим.
Шаг 1. Создание проекта
Для этого примера я созал новый Android Gradle проект и добавил в него проектой MainActivity:
Теперь создадим новый layout activity_main.xml как показанно в 12-й строке он нужн для нашего MainActivity:
Также не забудьте добавить activity в AndroidManifest.xml:
Обратите внимание что я использую не LinerLayout и не другие типы Layout-ов а GridView, но это не критично и вам не обязательно делать также. В этом примере мне не нужны другие layout поэтом я решил не использовать их.
GridView – компонент, который представляет данные в виде сетки. Инициализируется с помощью Адаптеров.
Также стоит обратить внимание на некоторые свойства компонента GridView:
android:numColumns=»auto_fit» – тут мы указываем количество колонок, так как установленно свойство auto_fit, то это количество будет определятся устройством.
android:id=»@+id/gridView» – мы указали ID чтобы иметь доступ к этому компоненту и добавлять элементы.
Шаг 2. Объект – элемент GridView
Теперь перед нами стоит задача заполнить наш GridView кнопками с именем продукта.
Для начало создадим наш продукт:
Этим объектом мы будем заполнять наш GridView.
Шаг 3. Создаём адаптер
Для того чтобы мы могли заполнить наш GridView созданым объектом во втором шаге нам нужно создать адаптер.
Создаем класс ProductAdapter и наслеуем его от BaseAdapter:
Как видите унаследовав BaseAdapter нам нужно было реализовать несколько методов, давайте их разберем.
Для начало нам нужно объявить наш список обектов (смотреть строку 15). Далее нужно создать переменую для контекста, он нам потребуется для заполнения обектов GridView.
int getCount() – должен возвращать количество элементов GridView, это наш список в строке 15;
Object getItem(int position) – возвращает эелемент с нашего GridView, где position – это индекс элемента в нашем списке;
long getItemId(int position) – возвращает id нашего элемента, в нашем случае он соответствует позиции.
View getView(int position, View convertView, ViewGroup parent) – должен возвращать элемент, который будет добавлен в GridView . Обычно тут создают и конфигурируют элемент для GridView .
Шаг 4. Применяем наш адаптер
Осталось применить наш адаптер для нашего GridView. Вернемся в MainActivity и в метод onCreate добавим создание списка наших продуктов:
После того как подготовили список продуктов, нужно применить наш адаптер к нашему GridView. Получаем GridView используя метод findViewById и после в строке 13 мы устанавливаем наш адаптер и в качестве параметра передаём контекст и список продуктов.
Источник
More Kotlin Android Tutorial
Kotlin GridView
In this tutorial you will learn about the Kotlin GridView and its application with practical example.
It displays items in a two-dimensional , scrollable grid. The ListView and GridView are subclass of AdapterView . As we discussed in ListView that Adapter is a bridge between UI and Data source and it retrieves data from data source.
Lets understand it by an example , Create GridView in Xml Layout like below code
android:id : it used to identify GridView Uniquely.
android:numColumns : It used to define that how many columns will be shown on display. It may be integer value like “2” or auto_fit. auto_fitmeans as many as column possible to fit on display.
android:verticalSpacing :It defines vertical spacing between rows, It can be dp,px,sp,in or mm.
android:horizontalSpacing :It defines horizontal spacing between columns.
android:strechMode :It defines how columns should stretched to fill display.
Example: With the help of below example we will get understand about GridView with Kotlin. There are some classes and xml which is used in Grid View are listed below.
- MainActivity
- LangListAdapter
- Langauge(Model).
- Activity_main.xml
- Layout_adapter.xml
- Header.xml
- border_layout.xml
Let’s get understand each class one by one.
#Langauge(Model): In Kotlin we do not need to write getter and setter method in model. It is very simple to create model in Kotlin support. Just check below model, you will get understand what I am trying to say.
so it is pretty simple to create model just need to declare our variable.
#LangListAdapter:Below is the Adapter Code, code is reduced by Kotlin and it is very easy to get understand, methods are same as we already discussed in BaseAdapter in Android Article. So Let’s write code of it. Here It extends Base Adapter which is clearly explained in Android Tutorial. BaseAdapter is very generic adapter which allows you to do pretty much whatever you want . Its custom Adapter from which you can do whatever you want to do with grid and list, But you need to do some coding for it.
Источник
Tutorialwing
In this article, we will learn about android GridView using Kotlin. We will go through various example that demonstrates how to use different attributes of GridView. For example,
In this article, we will get answer to questions like –
- What is GridView?
- Why should we consider GridView while designing ui for any app?
- What are possibilities using GridView while designing ui? etc.
Let’s have a quick demo of things we want to cover in this tutorial –
Output
Getting Started
We can define android GridView widget as below –
GridView is, a subclass of ViewGroup, a widget that are used to display items in 2-dimensional scrollable grid like view. You can use either BaseAdapter or ArrayAdapter or any other custom adapter to provide data in GridView.
Now, how do we use GridView in android application ?
Creating New Project
At first, we will create an application.
So, follow steps below to create any android project in Kotlin –
Step | Description |
---|---|
1. | Open Android Studio (Ignore if already done). |
2. | Go to File => New => New Project. This will open a new window. Then, under Phone and Tablet section, select Empty Activity. Then, click Next. |
3. | In next screen, select project name as GridView. Then, fill other required details. |
4. | Then, clicking on Finish button creates new project. |
Some very important concepts (Recommended to learn before you move ahead)
Before we move ahead, we need to setup for viewBinding to access Android GridView Using Kotlin file without using findViewById() method.
Setup ViewBinding
Add viewBinding true in app/build.gradle file.
Now, set content in activity using view binding.
Open MainActivity.kt file and write below code in it.
Now, we can access view in Kotlin file without using findViewById() method.
Using GridView in Kotlin
Follow steps below to use GridView in newly created project –
- Open res/values/strings.xml file. Then, add below code into it.
- Now, open res/values/dimens.xml file. Then, add below code into it.
Note – If there is no dimens.xml file in res/layout folder, then, you need to create this file.
Create View For Single Item in GridView
Now, you need to create a view for an item shown in gridView. So, create an xml file, named list_item.xml, in res/layout folder.
Now, open main/res/layout/list_item.xml file. Then, add below code into this file.
We are showing image and name of an item in gridView. So, there is imageView and textView in list_item.xml file.
Create Adapter For GridView
Now, we will create an customer adapter for GridView that will be used to provide data to it.
So, create a kotlin class, named ImageListAdapter.kt, file in main/java/com.tutorialwing.gridview folder. Then, add below code into it.
As we already know, this class provides data for an item to the GridView. We have inherited this class from ArrayAdapter class. A constructor has also been defined that accepts context, resourceId and itemList. resourceId is id of xml layout file of single item. Then, we have overridden some of the methods in this class.
S. No. | Method | Description |
---|---|---|
1. | getCount() | It returns the number of elements in item list provided to adapter class. Number of grids in gridView will be equal to number of elements |
2. | getView() | Returns the view at given position in the adapter. Here, It’s using class ItemHolder to recycle/reuse the already created View. Note that a view is created only when convertView is null. Otherwise, it’s returning already created view. |
Since adapter class is ready, we will use GridView widget in xml file. Then, we will access this GridView using kotlin file and perform some operations on it.
Open res/layout/activity_main.xml file. Then, add below code in it –
In activity_main.xml file, we have used gridView widget. This widget is responsible for providing view like grid. Now, we will access this gridView using kotlin file and perform some actions on it.
We can also access it in Kotlin File, MainActivity.kt, as below –
Here, we have accessed gridView using kotlin file i.e. In MainActivity.kt file. Then, an instance of ImageListAdapter class has been created. Then, this adapter class is set as an adapter of gridView.
After that we have set click listener (ItemClickListener) to gridView.
Now, run the application. We will get output as below –
Custom Adapter Using BaseAdapter
We can also create adapter for gridView by inheriting it from BaseAdapter. We can do it as below –
Create a new file, named ImageAdapter.kt, in main/java/com.tutorialwing.gridview folder. Then, add below code into it.
In this file, a single element contains only image. So, We can download all the drawable images here. Then, unzip the file and put all the images in res/drawable folder.
In this file, following methods have been overridden in this file –
S. No. | Method | Description |
---|---|---|
1. | getCount() | It returns the number of elements in item list provided to adapter class. Number of grids in gridView will be equal to number of elements |
2. | getView() | Returns the view at given position in the adapter. Here, It’s using class ItemHolder to recycle/reuse the already created View. Note that a view is created only when convertView is null. Otherwise, it’s returning already created view. |
3. | getItem() | Returns the item present at given position. |
4. | getItemId() | Returns the id of the item at given position. |
We can set this adapter in gridView as below –
Difference between BaseAdapter and ArrayAdapter
BaseAdapter is abstract while ArrayAdapter extends BaseAdapter. If you are using ArrayAdapter, you inherits all the features implemented in ArrayAdapter. But, if you are using BaseAdapter, you will have to implements all the abstract methods.
Different Attributes of GridView in XML
Now, we will see how to use different attributes of Android GridView using Kotlin to customise it –
Set Id of GridView
Many a time, we need id of View to access it in kotlin file or create ui relative to that view in xml file. So, we can set id of GridView using android:id attribute like below –
Here, we have set id of GridView as gridView_ID using android:id=”” attribute. So, if we need to reference this GridView, we need to use this id – gridView_ID.
Learn to Set ID of GridView Dynamically
Set Width of GridView
We use android:layout_width=”” attribute to set width of GridView.
We can do it as below –
Width can be either “MATCH_PARENT” or “WRAP_CONTENT” or any fixed value (like 20dp, 30dp etc.).
Learn to Set Width of GridView Dynamically
Set Height of GridView
We use android:layout_height=”” attribute to set height of GridView.
We can do it as below –
Height can be either “MATCH_PARENT” or “WRAP_CONTENT” or any fixed value.
Learn to Set Height of GridView Dynamically
Set Padding of GridView
We use android:padding=”” attribute to set padding of GridView.
We can do it as below –
Here, we have set padding of 10dp in GridView using android:padding=”” attribute.
Learn to Set Padding of GridView Dynamically
Set Margin of GridView
We use android:layout_margin=”” attribute to set margin of GridView.
We can do it as below –
Here, we have set margin of 10dp in GridView using android:layout_margin=”” attribute.
Learn to Set Margin of GridView Dynamically
Set Background of GridView
We use android:background=”” attribute to set background of GridView.
We can do it as below –
Here, we have set background of color #ff0000 in GridView using android:background=”” attribute.
Learn to Set Background of GridView Dynamically
Set Visibility of GridView
We use android:visibility=”” attribute to set visibility of GridView.
We can do it as below –
Here, we have set visibility of GridView using android:visiblity=”” attribute. Visibility can be of three types – gone, visible and invisible
Learn to Set Visibility of GridView Dynamically
Thus, we have seen what is GridView, how can we use android GridView using Kotlin ? etc. We also went through different attributes of android GridView.
Источник