ScrollView и HorizontalScrollView
При большом количестве информации, которую нужно поместить на экране приходится использовать полосы прокрутки. В Android существуют специальные компоненты ScrollView и HorizontalScrollView, которые являются контейнерными элементами и наследуются от ViewGroup. Обратите внимание, что класс TextView использует свою собственную прокрутку и не нуждается в добавлении отдельных полос прокрутки. Но использование отдельных полос даже с TextView может улучшить вид вашего приложения и повышает удобство работы для пользователя.
На панели инструментов компоненты можно найти в разделе Containers.
В контейнеры ScrollView и HorizontalScrollView можно размещать только один дочерний элемент (обычно LinearLayout), который в свою очередь может быть контейнером для других элементов. Виджет ScrollView, несмотря на свое название, поддерживает только вертикальную прокрутку, поэтому для создания вертикальной и горизонтальной прокрутки необходимо использовать ScrollView в сочетании с HorizontalScrollView. Обычно ScrollView используют в качестве корневого элемента, а HorizontalScrollView в качестве дочернего. Можно и наоборот, пробуйте.
В в теле метода onCreate() создайте ссылку на элемент TextView, объявленный в XML-разметке, и запишите в него через метод setText() какой-нибуль длинный текст, который не поместится в видимые размеры экрана устройства:
Запустив проект, вы должны увидеть вертикальную и горизонтальную полосы прокрутки при попытке скролирования.
Если полосы прокрутки вас раздражают, то используйте атрибут android:scrollbars=»none», который скроет их.
По такому же принципу можете вложить ImageView, чтобы просматривать большие картинки:
Методы scrollBy() и scrollTo()
Вы можете программно прокручивать контент с помощью методов scrollBy() и scrollTo(). Например, можно организовать автоматическую прокрутку во время чтения. В нашем примере мы будем прокручивать контент с помощью трёх кнопок.
Сам код для методов:
Дополнительное чтение
Библиотека ParallaxScrollView с использованием эффекта параллакса. Вы прокручиваете длинный текст, а задний фон прокручивается чуть медленнее. Возможно, кому-то пригодится. Там же можно скачать готовое демо и просмотреть в действии.
Источник
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.
Источник