- GridView
- Знакомьтесь — GridView
- Свойства
- Базовый пример
- GridView с картинками
- GridView с картинками и пояснительным текстом
- res/layout/cellgrid.xml
- Убрать вертикальную прокрутку
- Галерея
- Загружаем картинки из внешнего накопителя
- ImageAdapter.java
- Android ScrollView (Horizontal, Vertical) with Examples
- Android ScrollView Example
- activity_main.xml
- Output of Android ScrollView Example
- Android HorizontalScrollView Example
- activity_main.xml
- Output of Android HorizontalScrollView Example
- Android ScrollView (Horizontal, Vertical) with Examples
- Android ScrollView Example
- activity_main.xml
- Output of Android ScrollView Example
- Android HorizontalScrollView Example
- activity_main.xml
- Output of Android HorizontalScrollView Example
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
Код для главной активности:
В этом примере при щелчке выводится всплывающее сообщение. Вы можете запустить новую активность с показом выбранной картинки.
Источник
Android ScrollView (Horizontal, Vertical) with Examples
In android, ScrollView is a kind of layout that is useful to add vertical or horizontal scroll bars to the content which is larger than the actual size of layouts such as linearlayout, relativelayout, framelayout, etc.
Generally, the android ScrollView is useful when we have content that doesn’t fit our android app layout screen. The ScrollView will enable a scroll to the content which is exceeding the screen layout and allow users to see the complete content by scrolling.
The android ScrollView can hold only one direct child. In case, if we want to add multiple views within the scroll view, then we need to include them in another standard layout like linearlayout, relativelayout, framelayout, etc.
To enable scrolling for our android applications, ScrollView is the best option but we should not use ScrollView along with ListView or Gridview because they both will take care of their own vertical scrolling.
In android, ScrollView supports only vertical scrolling. In case, if we want to implement horizontal scrolling, then we need to use a HorizontalScrollView component.
The android ScrollView is having a property called android:fillViewport, which is used to define whether the ScrollView should stretch it’s content to fill the viewport or not.
Now we will see how to use ScrollView with linearlayout to enable scroll view to the content which is larger than screen layout in android application with examples.
Android ScrollView Example
Following is the example of enabling vertical scrolling to the content which is larger than the layout screen using an android ScrollView object.
Create a new android application using android studio and give names as ScrollViewExample. In case if you are not aware of creating an app in android studio check this article Android Hello World App.
Once we create an application, open activity_main.xml file from \res\layout folder path and write the code like as shown below.
activity_main.xml
If you observe above code, we used a ScrollView to enable the scrolling for linearlayout whenever the content exceeds layout screen.
Output of Android ScrollView Example
When we run the above example in android emulator we will get a result as shown below.
If you observe the above result, ScrollView provided a vertical scrolling for linearlayout whenever the content exceeds the layout screen.
As we discussed, ScrollView can provide only vertical scrolling for the layout. In case, if we want to enable horizontal scrolling, then we need to use HorizontalScrollView in our application.
We will see how to enable horizontal scrolling for the content which is exceeding the layout screen in the android application.
Android HorizontalScrollView Example
Now open activity_main.xml file in your android application and write the code like as shown below.
activity_main.xml
If you observe above code, we used a HorizontalScrollView to enable horizontal scrolling for linearlayout whenever the content exceeds layout screen.
Output of Android HorizontalScrollView Example
When we run the above example in the android emulator we will get a result like as shown below.
If you observe above result, HorizontalScrollView provided a horizontal scrolling for linearlayout whenever the content exceeds the layout screen.
This is how we can enable scrolling for the content which exceeds layout screen using ScrollView and HorizontalScrollView object based on our requirements.
Источник
Android ScrollView (Horizontal, Vertical) with Examples
In android, ScrollView is a kind of layout that is useful to add vertical or horizontal scroll bars to the content which is larger than the actual size of layouts such as linearlayout, relativelayout, framelayout, etc.
Generally, the android ScrollView is useful when we have content that doesn’t fit our android app layout screen. The ScrollView will enable a scroll to the content which is exceeding the screen layout and allow users to see the complete content by scrolling.
The android ScrollView can hold only one direct child. In case, if we want to add multiple views within the scroll view, then we need to include them in another standard layout like linearlayout, relativelayout, framelayout, etc.
To enable scrolling for our android applications, ScrollView is the best option but we should not use ScrollView along with ListView or Gridview because they both will take care of their own vertical scrolling.
In android, ScrollView supports only vertical scrolling. In case, if we want to implement horizontal scrolling, then we need to use a HorizontalScrollView component.
The android ScrollView is having a property called android:fillViewport, which is used to define whether the ScrollView should stretch it’s content to fill the viewport or not.
Now we will see how to use ScrollView with linearlayout to enable scroll view to the content which is larger than screen layout in android application with examples.
Android ScrollView Example
Following is the example of enabling vertical scrolling to the content which is larger than the layout screen using an android ScrollView object.
Create a new android application using android studio and give names as ScrollViewExample. In case if you are not aware of creating an app in android studio check this article Android Hello World App.
Once we create an application, open activity_main.xml file from \res\layout folder path and write the code like as shown below.
activity_main.xml
If you observe above code, we used a ScrollView to enable the scrolling for linearlayout whenever the content exceeds layout screen.
Output of Android ScrollView Example
When we run the above example in android emulator we will get a result as shown below.
If you observe the above result, ScrollView provided a vertical scrolling for linearlayout whenever the content exceeds the layout screen.
As we discussed, ScrollView can provide only vertical scrolling for the layout. In case, if we want to enable horizontal scrolling, then we need to use HorizontalScrollView in our application.
We will see how to enable horizontal scrolling for the content which is exceeding the layout screen in the android application.
Android HorizontalScrollView Example
Now open activity_main.xml file in your android application and write the code like as shown below.
activity_main.xml
If you observe above code, we used a HorizontalScrollView to enable horizontal scrolling for linearlayout whenever the content exceeds layout screen.
Output of Android HorizontalScrollView Example
When we run the above example in the android emulator we will get a result like as shown below.
If you observe above result, HorizontalScrollView provided a horizontal scrolling for linearlayout whenever the content exceeds the layout screen.
This is how we can enable scrolling for the content which exceeds layout screen using ScrollView and HorizontalScrollView object based on our requirements.
Источник