- ScrollView и HorizontalScrollView
- Методы scrollBy() и scrollTo()
- Custom View, скроллинг и жесты в Android на примере простого вьювера картинок
- Scroller com android app
- Android ScrollView,NestedScrollView,HorizontalScrollView etc
- 1. ScrollView
- ScrollView API Definition
- Important ScrollView methods
- Quick ScrollView Examples
- 2. NestedScrollView
- NestedScrollView API Definition
- Quick NestedScrollView Examples
- HorizontalScrollView
- HorizontalScrollView API Definition
- HorizontalScrollView Examples
- 4. StickyScrollView
- Installation
- How to Use it
- Full Example
- 5. Parallax Scroll
- ParallaxScrollView internal Details
- Installing ParallaxScroll
- Using ParallaxScroll
- Full ParallaxScroll Examples.
- Single Parallax ScrollView Example
- 4. SingleParallaxAlphaScrollView Example
- SingleParallax ExpandableListView Example
- Download
- How to Run
- Oclemy
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 с использованием эффекта параллакса. Вы прокручиваете длинный текст, а задний фон прокручивается чуть медленнее. Возможно, кому-то пригодится. Там же можно скачать готовое демо и просмотреть в действии.
Источник
Custom View, скроллинг и жесты в Android на примере простого вьювера картинок
В статье описываются детали реализации простого вьювера картинок и показываются некоторые тонкости имплементации скроллинга и обработки жестов.
И так, начнем. Ми будем разрабатывать приложения для просмотра картинок. Готовое приложение выглядит так (хотя скриншоты, конечно, слабо передают функционал):
Установить приложение можно либо из Маркета, либо установив вручную отсюда. Исходный код доступен здесь.
Главным элементом нашего приложения является класс ImageViewer который мы и будем разрабатывать. Но нужно также отметить, что для выбора файла для просмотра я не стал изобретать велосипед и взял готовый «компонент» здесь.
Компонент представляет собой activity, который вызывается при старте из главного activity. После выбора файла, мы его загружаем и показываем на экране с помощью класса ImageViewer. Рассмотрим класс более подробно.
Класс является наследником класса View и переопределяет только один его метод onDraw. Также класс содержит конструктор и метод загрузки изображения:
Если мы загрузим картинку по размерам больше чем экран смартфона, то отобразится только часть ее и у нас не будет способа ее подвинуть или уменьшить.
Добавим теперь возможность скроллинга. Скроллинг по своей сути представляет собой жест, при котором пользователь дотрагивается пальцем к экрану, передвигает его не отрывая, и отпускает. Для того чтоб иметь возможность обрабатывать события связанные с тач-скрином, нужно переопределить метод onTouchEvent. Метод принимает один параметр типа MotionEvent и должен возвратить true в случае обработки события. Через этот метод можно реализовать поддержку любого жеста, включая скроллинг.
Для распознавания скроллинга нам нужно зафиксировать момент дотрагивания, перемещения и отпускания. К счастью нету необходимости делать это вручную так как в Android SDK есть класс делающий всю работу за нас. Таким образом для того чтоб распознать жест скроллинга, нужно добавить в наш класс поле типа GestureDetector которое инициализируется объектом реализующим интерфейс OnGestureListener (именно этот объект будет получать события скроллинга). Также нужно переопределить метод onTouchEvent в классе ImageViewer и передавать обработку событий из него в наш объект типа OnGestureListener. Измененный класс ImageViewer (без неизмененных методов) представлен ниже:
Как видно на самом деле ми наследуем MyGestureListener не от OnGestureListener, а от SimpleOnGestureListener. Последний класс просто реализует интерфейс OnGestureListener с помощью пустых методов. Этим мы избавляем себя от реализации всех методов, выбирая только те, что нужно.
Теперь если загрузить большую картинку, мы, по крайней мере, сможем скролить ее. Но: во первых мы можем проскроллить за рамки картинки, во вторых нету скроллбаров, которые бы подсказали нам где мы находимся и сколько еще осталось до краев.
Решим для начала вторую проблему. Поиск в Интернет приводит нас к тому, что нужно переопределить методы computeHorizontalScrollRange и computeVerticalScrollRange. Эти методы должны возвратить реальные размеры картинки (на самом деле есть еще методы которые имеют отношение к скроллбарам – это методы computeHorizontalScrollExtent, computeHorizontalScrollOffset и такая же пара для вертикального скроллбара. Если переопределить и их, то тогда возвращать можно более произвольные значения). Но этого оказывается недостаточно – скроллбары в первых нужно включить, во вторых проинициализировать. Включаются они методами setHorizontalScrollBarEnabled и setVerticalScrollBarEnabled, инициализируются методом initializeScrollbars. Но вот незадача – последний метод принимает немного непонятный параметр типа TypedArray. Этот параметр должен содержать в себе набор стандартных для View атрибутов. Список можно увидеть здесь в таблице «XML Attributes». Если бы мы создавали наш view из XML, Android runtime бы автоматически составил такой список. Но так как мы создаем класс программно, нужно также создать этот список программно. Для этого нужно создать файл attrs.xml в каталоге res\values с таким содержимым:
В файле просто перечислены все атрибуты, которые были указаны в таблице, упомянутой выше (кроме некоторых на которые указывает компилятор как на ошибку – видимо в документации список приведен самый последний). Измененный класс ImageViewer (кроме неизменных методов):
Не хотелось бы на этом останавливаться, поэтому давайте добавим поддержку жеста «бросок» (fling). Этот жест есть просто дополнение к жесту скроллинга, но учитывается скорость перемещения пальца в последние моменты (перед отпусканием), и если она не нулевая, скроллинг продолжается с постепенным затуханием. Поддержка этого жеста уже заложена в GestureDetector – поэтому нам нужно всего лишь переопределить метод onFling в классе MyGestureListener. Отловив это событие нам нужно еще некоторое время изменять положение скроллинга. Конечно, это можно сделать «вручную» с помощью таймеров или еще как, но опять же в Android SDK уже есть класс, реализующий нужный функционал. Поэтому нужно добавить в класс ImageViewer еще одно поле типа Scroller, которое и будет заниматься «остаточным» скроллингом – для старта скроллинга нужно вызвать его метод fling. Также нужно показать скроллбары (они ведь прячутся когда не нужны) вызовом метода awakenScrollBars. И последнее что нужно сделать – это переопределить метод computeScroll, который должен непосредственно делать скроллинг с помощью метода scrollTo (класс Scroller сам не занимается скроллингом – он просто работает с координатами). Код измененного класса ImageViewer представлен ниже:
В завершения разговора о жесте fling надо сделать одну мелочь – при прикосновении пальцем во время скроллинга от броска, нужно остановить скроллинг. На этот раз мы это сделаем «вручную» в методе onTouchEvent. Измененный метод представлен ниже:
Уже можно любоваться достаточно интересной физикой, но можно увидеть некоторые «глюки» при скроллинге за пределы картинки. Это происходит из-за того, что fling работает только в пределах картинки, а скроллинг без броска работает везде. Т.е. мы сможем выйти за рамки картинки только если очень плавно скролить (чтоб не срабатывал fling). Исправить этот «косяк» можно путем введения ограничение на обработку в метод onFling и обрабатывать бросок только если он не выходит за границы картинки. Измененный метод представлен ниже:
Теперь мы опять можем беспрепятственно скролить за рамки картинки. Кажется, эту проблему мы уже вспоминали… У нее есть элегантное решение, лежащее в том, что при отпускании пальца (при завершении скроллинга за рамками картинки) нужно картинку плавно вернуть в «положенное» место. И опять мы это сделаем «вручную» в методе onTouchEvent:
Вот теперь с уверенностью можно сказать что со скроллингом мы разобрались. Можем переходить к последнему жесту который хотелось бы реализовать – это жест pinch zoom.
Со стороны жест выглядит как растягивание или сжатие чего-то воображаемого на экране смартфона двумя пальцами. Пошагово жест происходит так: нажатие одним пальцем, нажатие вторым пальцем, изменение положения одного или двух пальцев не отпуская, отпускание второго пальца. Для определения величины масштабирования нужно вычислить соотношение между расстояниями между пальцами в момент начала жеста и в момент окончания жеста. Расстояние между пальцами находится по формуле sqrt(pow(x2 – x1, 2) + pow(y2 – y1, 2)). Также нужно отметить некоторое положение скроллинга которое нужно сохранять – ведь если жестом увеличить картинку, то положение скроллинга изменится (из-за измененного размера картинки). Это положение – а точнее точка, положение которой нужно сохранить, в терминологии Android SDK называется фокальной точкой, и находиться она посередине между двумя пальцами.
Реализовать жест как всегда можно самому, но и это к счастью уже реализовано в Android SDK (правда, только начиная с версии 2.2). Поможет в этом класс ScaleGestureDetector, инстанс которого добавим в наш класс. ScaleGestureDetector инициализируется обьектом, поддерживающим интерфейс OnScaleGestureListener, поэтому создадим также внутренний класс MyScaleGestureListener, который реализует методы onScaleBegin, onScale и onScaleEnd. Не забываем передать управление ScaleGestureDetector из метода onTouchEvent. Ну и самое главное – нужно как-то использовать данные масштабирования: их нужно учитывать во всех местах, где раньше фигурировали ширина и высота картинки (т.е. фактически нужно умножить эти параметры на коэффициент масштабирования). Финальный код класса ImageViewer можно посмотреть в исходниках.
На этом все. Надеюсь статься окажется полезной.
Источник
Scroller com android app
The library is a RecyclerView-based implementation of a scrollable list, where current item is centered and can be changed using swipes. It is similar to a ViewPager, but you can quickly and painlessly create layout, where views adjacent to the currently selected view are partially or fully visible on the screen.
Add this into your dependencies block.
Reporting an issue
If you are going to report an issue, I will greatly appreciate you including some code which I can run to see the issue. By doing so you maximize the chance that I will fix the problem.
By the way, before reporting a problem, try replacing DiscreteScrollView with a RecyclerView. If the problem is still present, it’s likely somewhere in your code.
Please see the sample app for examples of library usage.
The library uses a custom LayoutManager to adjust items’ positions on the screen and handle scroll, however it is not exposed to the client code. All public API is accessible through DiscreteScrollView class, which is a simple descendant of RecyclerView.
If you have ever used RecyclerView — you already know how to use this library. One thing to note — you should NOT set LayoutManager.
- Add DiscreteScrollView to your layout either using xml or code:
- Create your implementation of RecyclerView.Adapter. Refer to the sample for an example, if you don’t know how to do it.
- Set the adapter.
- You are done!
Related to the current item:
One useful feature of ViewPager is page transformations. It allows you, for example, to create carousel effect. DiscreteScrollView also supports page transformations.
In the above example view1Position == (currentlySelectedViewPosition — n) and view2Position == (currentlySelectedViewPosition + n) , where n defaults to 1 and can be changed using the following API:
Because scale transformation is the most common, I included a helper class — ScaleTransformer, here is how to use it:
You may see how it works on GIFs.
Slide through multiple items
To allow slide through multiple items call:
The default threshold is set to 2100. Lower the threshold, more fluid the animation. You can adjust the threshold by calling:
Infinite scroll is implemented on the adapter level:
An instance of InfiniteScrollAdapter has the following useful methods:
Currently InfiniteScrollAdapter handles data set changes inefficiently, so your contributions are welcome.
It’s possible to forbid user scroll in any or specific direction using:
Where config is an instance of DSVScrollConfig enum. The default value enables scroll in any direction.
Thanks to Tayisiya Yurkiv for sample app design and beautiful GIFs.
Источник
Android ScrollView,NestedScrollView,HorizontalScrollView etc
In this piece we want to look at several scrollview variations or subclasses and how they are used. Here are the variations we cover so far:
- ScrollView – Superclass
- NestedScrollView – child class
- HorizontalScrollView – child class
- StickyScrollView – Child class and third party library.
- ParallaxScrollView – child class and third party library
1. ScrollView
Android ScrollView Tutorials and Examples
A ScrollView is an android layout that permits it’s child views to be scrolled vertically. This is important because in many cases you need content to be scrolled. Normally adapterviews like ListView and recyclerview have scrolling capability but not many views. Hence we don’t use scrollview with them otherwise we get degraded performance.
With scrollview you only scroll up or down. However if you want horizontal scrolling then you can use the HorizontalScrollView.
Furthermore, ScrollView should only have one direct child. This then means that if you desire to add multiple children then use a ViewGroup like relativelayout or LinearLayout. Then add those children to the viewgroup and the viewgroup to Scrollview.
Android Engineeres are recommending that you use NestedScrollView instead of ScrollView for vertical scrolling.
This is because the latter offers greater user interface flexibility and support for the material design scrolling patterns.
ScrollView API Definition
A scrollview as a class resides in the android.widget package and derives from FrameLayout:
Here’s the inheritance hierarchy of FrameLayout:
Important ScrollView methods
(a). scrollTo(int x, int y)
In this method you pass the scrolled position of your view. This version also clamps the scrolling to the bounds of our child.
(b). smoothScrollTo(int x, int y)
Like scrollTo(int, int) , but scroll smoothly instead of immediately.
(c). getChildAt(int index)
This method will return the view at the specified position in the group.
(d). getChildCount()
This method returns the number of children in the group.
Quick ScrollView Examples
1. ScrollView – How to Scroll to the Top
Let’s see how you can scroll to the top of your scrollview.
2. How to Scroll to Down in ScrollView
Then we want to see also how we can scroll down to the bottom of our scrollview programmatically.
It’s a static method and we pass ScrollView instance as a parameter. First we get the height of the scrollview as we as it’s child counts.
At the end of the day we are still using the scrollTo() method, passing in the x and y positions.
3. How to smooth scroll to up
We use the smoothScrollTo() method and pass the positions.
4. How to smooth scroll to Down
Here’s how we can scroll to down programmatically.
5. How to calculate height of ScrollView by Child View
6. How to create a scrollview with maximum height limit
What if we desire to set the maximum height limit to our scrollview. Well we can simply create a custom scrollview by deriving from the android.widget.ScrollView class, override our constructors as well as the onMeasure() method.
7. Full ScrollView Example
Let’s look a full scrollview example.
(a). MainActivity.java
(b). activity_main.xml
2. NestedScrollView
Android NestedScrollView Tutorials and Examples.
NestedScrollView is a ScrollView that is able to act as a nested scrolling parent and child on both new and old versions of Android.
Nested scrolling is enabled by default in NestedScrollView.
NestedScrollView is recommended in many cases over ScrollView.
This is due it’s ability to offer greater user interface flexibility and support for the material design scrolling patterns.
NestedScrollView API Definition
NestedScrollView was added in android version 22.1.0 and belongs to Maven artifact com.android.support:support-compat:latest_version .
Like ScrollView, nested scrollview derives from FrameLayout.
However it goes further and implements three scrolling interfaces:
- NestedScrollingParent – an interface implemented by [ViewGroups(/android/viewgroup)] that wish to support scrolling operations delegated by a nested child view.
- NestedScrollingChild2 – an interface implemented by View subclasses that wish to support dispatching nested scrolling operations to a cooperating parent ViewGroup.
- ScrollingView – An interface that can be implemented by Views to provide scroll related APIs.
Here’s the inheritance hierarchy for nestedscrollview:
You can find complete API reference in android developer documenattion.
Quick NestedScrollView Examples
1. How to Calculate NestedScrollView Height by it’s child view
HorizontalScrollView
Android HorizontalScrollView Tutorial and examples.
A HorizontalScrollView is a Layout container for a view hierarchy that can be scrolled by the user, allowing it to be larger than the physical display.
You use HorizontalScrollView, as the name suggests, to scroll horizontally. If you want to scroll vertically then you can use ScrollView or even better NestedScrollView.
All these «ScrollViews», HorizontalScrollView included, derive from the FrameLayout.
Hence you should strive to place only a single child. Then that child can have multiple other views.
Alot of people love using LinearLayout with horizontal orientation. Thus providing a nice and easy way of showing and then scrolling through views arranged nicely horizontally.
Beware that some views are capable of handling their own scrolling. Such is the textView. So it doesn’t require HorizontalScrollView.
HorizontalScrollView API Definition
HorizontalScrollView was added in API level 3 so is actually than you might think.
We said it derives from FrameLayout
Here’s it’s inheritance tree:
HorizontalScrollView Examples
4. StickyScrollView
StickyScrollView is a library that provides you with a scrollview with a custom header and footer. It is really ideal for showing details, for example product details. As you may know scrollview is a layout that permits its children to be scrolled.
Well StickScrollview provides you with the same capability as scrollview but allows you to add a header and footer.
StickyScrollView is written in Java and extends ScrollView class:
Installation
StickScrollView is hosted in Maven jitpack so to install first go to your root level build/gradle and register jitpack as a repository:
Then you add it as a dependency:
How to Use it
Well its a layout so its usage is very simple:
Full Example
Well first install as instructed above. Then make sure your minimum API level is API 16 or above.
(a). activity_main.xml
(b). MainActivity.java
First add your imports, including the StickyScrollView library:
Then create your activity class:
Define StickyScrollView as an instance field:
Reference views in your onCreate() method:
Now handle click events:
Here is the full code:
Here is the demo:
Special thanks to @amarjain07 for this awesome library and example.
5. Parallax Scroll
Android Paralax Scroll Library Tutorial and Example.
ParallaxScroll is a library that provides us with Parallax ScrollView and ListView for Android.
ParallaxScroll enriches us with these special adapterviews:
- ParallaxListView.
- ParallaxExpandableListView.
- ParallaxScrollView.
This library was created by Nir Hartmann.
The library has existed for more than 5 years and is still actively maintained. It also has examples which we will explore later on.
ParallaxScroll supports Android 1.6 and above.
Android Parallax Scroll
See the demo app at Google Play here.
ParallaxScrollView internal Details
Let’s explore the internal specifics of Parallax before jumping to usage examples. We want to see the several classes from which the library is built so that we can even extend.
(a). ParallaxScrollView
This is class that internally derives from ScrollView.
You all know that a scrollview is a Layout container for a view hierarchy that can be scrolled by the user, allowing it to be larger than the physical display.
Like most View resources, ParallaxScrollView exposes three public constructors:
(a). ParallaxListView
ParallaxListView derives from the ListView class:
It also has three constructors we can use to create it’s instance:
It goes ahead and exposes us some methods we can use apart from the normall ListView methods:
(c). ParallaxExpandableListView
ParallaxExpandableListView adds parallax scroll to an ExpandableListView from which it derives.
This class provides us two constructors for object creation:
Here are some of the methods we can use apart from those we derive from ExpandableListView.
Installing ParallaxScroll
You can install ParallaxScroll from it’s maven repository via gradle.
All you need in android 1.6 and above. Then you add the following implementation statement in your app level build.gradle:
Then you sync the project to add the library files into your project.
Using ParallaxScroll
Let’s say you want to use a ScrollView , then you can add the following in your layout.
In that case we’ve used a ParallaxScrollView and placed inside it a LinearLayout with Text content that will be scrolled.
Well you can also add a ParallaxListView and ParallaxExpandableListView in your layout.
Full ParallaxScroll Examples.
Here’s an example.
1. Single Parallax ListView example.
Let’s start by looking at a our SingleParallaxListView example.
(a). CustomListAdapter.java
We start by writing our adapter class. It will derive from BaseAdapter.
(b). SingleParallaxListView.java
This is our activity class. This activity will contain our ParallaxListView.
(c). list_one_parallax.xml
You can see this is the layout that will be inflated into our SingleParallaxListView .
2. Multi Parallax ListView example.
We are using the CustomListAdapter we had already defined.
(a). MultipleParallaxListView.java
(b) list_multiple_parallax.xml
Single Parallax ScrollView Example
Let’s now look at single parallax scrollview example.
(a). SingleParallaxScrollView.java
(b) scroll_one_parallax.xml
4. SingleParallaxAlphaScrollView Example
(a) SingleParallaxAlphaScrollView.java
(b) scroll_one_parallax_alpha.xml
SingleParallax ExpandableListView Example
(a) CustomExpandableListAdapter.java
(b) SingleParallaxExpandableListView.java
(c) expand_list_one_parallax.xml
You can get full source samples below:
Download
Also check our video tutorial it’s more detailed and explained in step by step.
No. | Location | Link |
---|---|---|
1. | GitHub | Direct Download |
2. | GitHub | Library |
3. | Google Play | Demo App |
Credit to the Original Creator @nirhart
How to Run
- Download the project.
- Go over to sample folder and edit import it to your android studio.Alternatively you can just copy paste the classes as well as the layouts and maybe other resources into your already created project.
- Then edit the app level build/gradle to add our dependency as we had stated during the installation.
report this ad
Oclemy
Thanks for stopping by. My name is Oclemy(Clement Ochieng) and we have selected you as a recipient of a GIFT you may like ! Together with Skillshare we are offering you PROJECTS and 1000s of PREMIUM COURSES at Skillshare for FREE for 1 MONTH. To be eligible all you need is by sign up right now using my profile .
Источник