- GridLayout
- Цифровая клавиатура
- RecyclerView using GridLayoutManager in Android With Example
- How to use RecyclerView as GridView?
- Difference Between RecyclerView and GridView
- Example of GridLayoutManager in RecyclerView
- Step by Step Implementation
- RecyclerView as Staggered Grid in Android With Example
- Example
- Step by Step Implementation
- Android GridLayoutManager Example
- Android Tutorial
- Android GridLayoutManager
- Android GridLayoutManager Example Project Structure
GridLayout
В Android 4.0 появился новый вид макета под именем GridLayout (раздел Layouts на панели инструментов). На первый взгляд он может показаться похожим на TableLayout. Но на самом деле он гораздо удобнее и функциональнее. И очень рекомендуется изучить и использовать его в своих новых проектах, которые разрабатываются под новую платформу.
Позже в библиотеку совместимости добавили класс android.support.v7.widget.GridLayout, который позволяет использовать компонент и для старых устройств. Найти его можно в разделе AppCompat.
Разметка относится к классу android.widget.GridLayout и имеет колонки, ряды, клетки как в TableLayout, но при этом элементы могут гибко настраиваться.
В GridLayout для любого компонента можно указать строку и колонку, и в этом месте таблицы он будет размещён. Указывать элемент для каждой ячейки не понадобится, это нужно делать только для тех ячеек, где действительно должны быть компоненты. Компоненты могут растягиваться на несколько ячеек таблицы. Более того, в одну ячейку можно поместить несколько компонентов.
В данной разметке нельзя использовать атрибут веса, поскольку он не сработает в дочерних представлениях GridLayout. Используйте атрибут layout_gravity.
Обратите внимание на атрибуты layout_column и layout_columnSpan, используемые для указания самой левой колонки и количества занимаемых компонентом колонок. Также доступны атрибуты layout_row и layout_rowSpan.
Для дочерних элементов не нужно указывать атрибуты layout_height и layout_width, по умолчанию они устанавливаются в значение wrap_content.
Количество колонок и рядов используются атрибуты android:columnCount=»number» и android:rowCount=»number».
Цифровая клавиатура
Для демонстрации создадим пример цифровой клавиатуры или калькулятора, чтобы понять преимущества нового шаблона.
Итак, мы хотим создать разметку, напоминающую цифровую панель на многих моделях клавиатур для настольного компьютера или обычный калькулятор. Если вы посмотрите на цифровую панель, то увидите, что часть клавиш имеет больший размер и вытянуты в длину или ширину. Подобный дизайн практически невозможно реализовать старыми способами — придётся постоянно использовать вложенные конструкции LinearLayout, TableLayout и др.
Но, теперь у нас есть GridLayout. Во многом его поведение схоже с LinearLayout — у него есть горизонтальная и вертикальная ориентации, которые определяют вывод следующего элемента.
Для цифровой клавиатуры, если начнем с клавиши слэша (/) с позиции 4 колонки, то используя горизонтальную ориентацию, нам не нужно пропускать клетки. Выбирая горизонтальную ориентацию, мы ограничиваем число колонок для автоматического переноса новой клетки на следующий ряд. В нашем примере используется четыре колонки. В каждой клетке макета будет находиться кнопка, отцентрированая относительно клетки. Сама разметка должна занимать весь контент экрана.
Дочерние элементы настраиваются не совсем привычном образом. Нам не нужно явно задавать размеры (ширину и высоту) каждого элемента. Согласно нашему плану мы должны использовать четыре колонки для 16 кнопок. Попробуем.
Вот как будет выглядеть первоначальная XML-разметка для нашей цели:
А так будет выглядеть форма в графическом дизайнере:
Поиграйтесь с параметром android:columnCount, чтобы увидеть, как ведёт себя шаблон при разных значениях.
Теперь займёмся более точной настройкой. Например, первая клавиша клавиатуры — символ слеша (/) будет иметь такой же размер, как большинство кнопок, но начинаться с четвёртой колонки. Клавиша (+) идёт после клавиши (9) и занимает три воображаемых ряда. Клавиша (0) должна занять две колонки. Клавиша (=) должна занять три колонки. Внесём требуемые изменения:
Теперь мы видим такую картину:
Это не совсем то, что нам нужно. Вроде клавиши зарезервировали себе место, но не растянулись до нужных размеров. Исправляем ситуацию. Здесь на помощь нам придёт атрибут layout_gravity. Применим его у клавиш, которые необходимо растянуть:
Финальный результат радует глаз:
Как видите, если разобраться, то ничего сложного. Разметка получилась лаконичной и удобной для чтения.
Источник
RecyclerView using GridLayoutManager in Android With Example
RecyclerView is the improvised version of a ListView in Android. It was first introduced in Marshmallow. Recycler view in Android is the class that extends ViewGroup and implements Scrolling Interface. It can be used either in the form of ListView or in the form of Grid View.
How to use RecyclerView as GridView?
While implementing Recycler view in Android we generally have to set layout manager to display our Recycler View. There are two types of layout managers for Recycler View to implement.
- Linear Layout Manager: In linear layout manager, we can align our recycler view in a horizontal or vertical scrolling manner by specifying its orientation as vertical or horizontal.
- Grid Layout Manager: In Grid Layout manager we can align our recycler in the form of a grid. Here we have to mention the number of columns that are to be displayed in the Grid of Recycler View.
Difference Between RecyclerView and GridView
1. View Holder Implementation
In GridView it was not mandatory to use View holder implementation but in RecyclerView it is mandatory to use View Holder implementation for Recycler View. It makes the code complex but many difficulties that are faced in GridView are solved in RecyclerView.
2. Performance of Recycler View
RecyclerView is an improvised version of ListView. The performance of Recycler View has been improvised. In RecyclerView the items are ahead and behind the visible entries.
Example of GridLayoutManager in RecyclerView
A sample image is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
Step by Step Implementation
Step 1: Create a New Project in Android Studio
To create a new project in Android Project just refer to this article on How to Create new Project in Android Studio and make sure that the language is Java. To implement Recycler View three sub-parts are needed which are helpful to control RecyclerView. These three subparts include:
- Card Layout: The card layout is an XML file that will represent each individual grid item inside your Recycler view.
- View Holder: View Holder Class is the java class that stores the reference to the UI Elements in the Card Layout and they can be modified dynamically during the execution of the program by the list of data.
- Data Class: Data Class is an object class that holds information to be displayed in each recycler view item that is to be displayed in Recycler View.
Step 2: Add google repository in the build.gradle file of the application project.
All Jetpack components are available in the Google Maven repository, include them in the build.gradle file
Step 3: Create a Card Layout for Recycler View Card Items
Источник
RecyclerView as Staggered Grid in Android With Example
GridView: A ViewGroup that shows the items in a two-dimensional scrolling grid. In Grid View, each grid is of the same size .i.e., the height and width of each grid are equal. It shows symmetric items in the views.
Staggered GridView: This ViewGroup is the extension of Grid View. In this view, the Grid is of varying size .i.e., their height and width may vary. It shows asymmetric items in the views. It automatically sets the item views according to its height and width.
In order to use RecyclerView for creating staggering grid views, we need to use StaggeredGridLayoutManager. LayoutManager is responsible for measuring and positioning item views in the RecyclerView and also recycle the item views when they are no longer visible to the user. There are three types of built-in layout managers.
- LinearLayoutManager: It is used to show item views in a vertical and horizontal list.
- GridLayoutManager: It is used to show item views grid views.
- StaggeredLayoutManager: It is used to show item views in staggered views.
We can also create a custom layout manager by RecyclerView.LayoutManager class.
StaggeredGridLayoutManager(int spanCount, int orientation)
- Creates staggered grid layout with given parameters
- The first parameter, spanCount is used to set the number of columns in a vertical orientation or the number of rows in the horizontal orientation
- The second parameter, orientation is used to set the vertical or horizontal orientation
Staggered Grid with Vertical Orientation
RecyclerView recyclerView = (RecyclerView)findViewById(R.id.recyclerView);
// staggeredGridLayoutManager with 3 columns and vertical orientation
StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(3, LinearLayoutManager.VERTICAL);
// setting recycler view layout to staggered grid
Staggered Grid with Horizontal Orientation
RecyclerView recyclerView = (RecyclerView)findViewById(R.id.recyclerView);
// staggeredGridLayoutManager with 3 rows and horizontal orientation
StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(3, LinearLayoutManager.HORIZONTAL);
// setting recycler view layout to staggered grid
Example
In this example, we would store data into ArrayList which is used for populating RecyclerView. After that we set the layout manager of RecyclerView as a staggered grid view and then, we set the Adapter for RecyclerView to show item views. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
Step by Step Implementation
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Adding dependencies
Источник
Android GridLayoutManager Example
Android Tutorial
Android GridLayoutManager is the RecyclerView.LayoutManager implementation to lay out items in a grid. In this tutorial, we’ll create an application that displays CardViews inside a RecyclerView in the form of a GridLayout. Also, we’ll implement an interface that makes RecyclerView item click similar to a ListView itemClickListener .
Android GridLayoutManager
We’ve implemented a RecyclerView using a LinearLayoutManager here. Now let’s use a GridLayoutManager to layout the RecyclerView as a grid.
Following is the constructor for a GridLayoutManager.
reverseLayout if set true then layout items from end to start.
To set the span size for each item, we invoke the method setSpanSizeLookup on the GridLayoutManager
Let’s implement RecyclerView using a GridLayoutManager in a new Android Studio project.
Android GridLayoutManager Example Project Structure
The project consists of a single Activity : MainActivity.java , an adapter class : RecyclerViewAdapter.java , a DataModel.java class and a custom GridLayoutManager class AutoFitGridLayoutManager.java .
The xml layout of the MainActivity.java class is defined in the file activity_main.xml as
Note: Don’t forget to add the following dependencies for Material Design widgets and CardView in the build.gradle file.
The DataModel.java class is given below:
package com.journaldev.recyclerviewgridlayoutmanager;
The DataModel class will hold the text, drawable icon and background colour of each item cell.
The RecyclerViewAdapter.java class is given below:
In the above code we’ve defined an ItemListener interface that’ll be implemented in the MainActivity.java class.
The xml layout for each RecyclerView item is given below.
recycler_view_item.xml
The AutoFitGridLayoutManager.java class is given below:
The span count is dynamically calculated based on the orientation, width and height available.
The MainActivity.java class is given below:
- The above class implements the interface RecyclerViewAdapter.ItemListener and overrides the method onItemClick that’s defined in the adapter class. By doing this, we’ve implemented the RecyclerView Click Listener within our Activity instead of the Adapter class(similar to the standard onItemClickListener defined for a ListView)
- A DataModel class holds the details for each RecyclerView item
- The LayoutManager of the RecyclerView can be defined by either instantiating the AutoFitGridLayoutManager class with the column width set as 500 or by invoking the GridLayoutManager class object and setting the number of columns as 2
Let’s see the output of the application with the standard GridLayoutManager code.
As you can see, each row has two items that span the column width in both orientations.
Now comment out the code for simple GridLayoutManager and run the code for AutoFitGridLayoutManager
The output of the application in action is given below.
As you can see in the above output, when the orientation changes to landscape, each row has three items, thereby dynamically sizing the items to auto-fit the column width.
This brings an end to this tutorial. You can download the final android GridLayoutManager project from the link given below.
Источник