Android studio sliding panel

Sliding экранов внутри приложения

Современные мобильные устройства в первую очередь ориентированы на управление пальцами, в частности жестами и прикосновениями. Эта особенность добавляет определенную специфику в организацию пользовательских интерфейсов. На главную роль выходят интуитивно понятные решения, требующие от пользователя наименьших усилий и при этом ненавязчивые, сохраняющие максимум полезного пространства, т.е. не загромождающие пользовательский интерфейс.

Примером таких решений является переключение между рабочими экранами в Android, где для перемещения от одного экрана к другому достаточно выполнить жест вправо или влево. О возможной реализации подобного решения и пойдет речь в данном посте.

Вместо вступления

Для того чтобы проиллюстрировать, то о чем будет идти речь далее, и тем самым добавить наглядности, я записал небольшое видео работы приложения, которое я сегодня буду делать:

В показанном выше приложении имеются четыре несвязанные View, перемещение между которыми осуществляется жестами вправо/влево по экрану. Содержание View могло быть произвольное, но для простоты восприятия я сделал их разноцветными и пронумерованными.

Подобная функциональность не является базовой, т.е. не имеет полностью готового встроенного решения. А также, как ни странно, не является сильно распространенной, и, наверно, из-за этого не освещена в интернете в достаточной степени.

Разработка

Для реализации приведенного приложения необходимо выполнить следующие шаги:

  1. Найти или реализовать контейнер для удобного хранения и перемещения между View
  2. Перехватить пользовательские жесты и на основании полученной информации сделать вывод в какую сторону «двигать» view
  3. Добавить анимацию для визуализации перемещений между экранами

К счастью, контейнер, отвечающий нашим требованиям, уже присутствует в арсенале Android, называется он ViewFlipper. Создадим пустой проект, и добавим в основной layout элемент ViewFlipper:

Теперь создадим четыре view между которыми будем перемещаться, в моем примере они имеют вид:

Далее необходимо связать имеющиеся view c ViewFlipper. Для этого в методе OnCreate базового Activity добавим следующий код:

Теперь мы можем перемещаться между view вызовами методов showNext() и showPrevious() объекта flipper.

Жесты пользователя возбуждают события OnTouch, для обработки этих событий необходимо реализовать метод:

В этом методе, в объекте класса MotionEvent, присутствует вся необходимая информация и выполненном жесте.

Т.к. нам нужно понять куда был выполнен жест вправо или влево, то мы поступим очень просто: сохраним координату по оси X, при нажатии на экран, и сравним с координатой после того как экран будет отпущен. Если изначальное значение больше, то это движение влево, иначе вправо. Код выглядит достаточно просто:

Осталось добавить анимацию. ViewFlipper как и все наследники ViewAnimator поддерживает методы: setInAnimation(. ) и setOutAnimation(. ), через которые можно задать анимации (Animation) вхождения view в экран и пропадания view с экрана. Но т.к. наша анимация будет отличаться в зависимости от жестов, то придется ее указывать каждый раз заново, исходя из текущей операции. Т.е. метод onTouch нужно модифицировать следующим образом:

Где R.anim.* ресурсы с анимацией появления и исчезания view. Не буду приводить все четыре варианта приведу только первый (все остальные можно будет посмотреть в примере проекта, который я приложу к посту):

Все готово! Проект с примером можете скачать отсюда.

UPD. Вариант ViewFlipper’а без отпускания пальца (изменение метода onTouch):

UPD 2. Если вам больше нравится слайдинг с предпросмотром следующей страницы, то вы можете присмотреться к решениям без ViewFlipper, на базе ViewGroup и scrollTo, пример можете найти, например, здесь.

Читайте также:  Social mobiles для android

Заключение

Основное достоинство sliding’а, при правильном его использовании: разгрузка пользовательского интерфейса от избыточных контролов. Как видно, реализация получилась простой, а применение подобного функционала поистине широкое.

Но ложка дегтя все же присутствует. Во-первых, если взглянуть на мой пример в первый раз, то практически невозможно догадаться, что там присутствует sliding (это пример и здесь я такой задачи не ставил), а следовательно применение sliding’а требует наличие других UI-решений поясняющих наличие этого самого sliding’а, например, на тех же home screen’ах Android есть «ползунок-индикатор» показывающий на каком экране находится в данный момент пользователь. Во-вторых, при наличии на view контролов, имеющих собственную реакцию на нажатия, прокрутки, и т.п., вызов метода onTouch внутри ViewFlipper’а будет заблокирован его более ранним перехватом внутри дочернего view, поэтому придется дополнительно побеспокоиться о пробрасывании этого события «наверх» к ViewFlipper.

Источник

Android studio sliding panel

Android Sliding Up Panel

This library provides a simple way to add a draggable sliding up panel (popularized by Google Music and Google Maps) to your Android application.

As seen in Umano Android App (now acquired by Dropbox):

Known Uses in Popular Apps

  • [Soundcloud] (https://play.google.com/store/apps/details?id=com.soundcloud.android)
  • [Dropbox Paper] (https://play.google.com/store/apps/details?id=com.dropbox.paper)
  • [Snaptee] (https://play.google.com/store/apps/details?id=co.snaptee.android)

If you are using the library and you would like to have your app listed, simply let us know.

Importing the Library

Simply add the following dependency to your build.gradle file to use the latest version:

  • Include com.sothree.slidinguppanel.SlidingUpPanelLayout as the root element in your activity layout.
  • The layout must have gravity set to either top or bottom .
  • Make sure that it has two children. The first child is your main layout. The second child is your layout for the sliding up panel.
  • The main layout should have the width and the height set to match_parent .
  • The sliding layout should have the width set to match_parent and the height set to either match_parent , wrap_content or the max desireable height. If you would like to define the height as the percetange of the screen, set it to match_parent and also define a layout_weight attribute for the sliding view.
  • By default, the whole panel will act as a drag region and will intercept clicks and drag events. You can restrict the drag area to a specific view by using the setDragView method or umanoDragView attribute.

For more information, please refer to the sample code.

For smooth interaction with the ActionBar, make sure that windowActionBarOverlay is set to true in your styles:

However, in this case you would likely want to add a top margin to your main layout of ?android:attr/actionBarSize or ?attr/actionBarSize to support older API versions.

Caveats, Additional Features and Customization

  • If you are using a custom umanoDragView , the panel will pass through the click events to the main layout. Make your second layout clickable to prevent this.
  • You can change the panel height by using the setPanelHeight method or umanoPanelHeight attribute.
  • If you would like to hide the shadow above the sliding panel, set shadowHeight attribute to 0.
  • Use setEnabled(false) to completely disable the sliding panel (including touch and programmatic sliding)
  • Use setTouchEnabled(false) to disables panel’s touch responsiveness (drag and click), you can still control the panel programatically
  • Use getPanelState to get the current panel state
  • Use setPanelState to set the current panel state
  • You can add parallax to the main view by setting umanoParallaxOffset attribute (see demo for the example).
  • You can set a anchor point in the middle of the screen using setAnchorPoint to allow an intermediate expanded state for the panel (similar to Google Maps).
  • You can set a PanelSlideListener to monitor events about sliding panes.
  • You can also make the panel slide from the top by changing the layout_gravity attribute of the layout to top .
  • You can provide a scroll interpolator for the panel movement by setting umanoScrollInterpolator attribute. For instance, if you want a bounce or overshoot effect for the panel.
  • By default, the panel pushes up the main content. You can make it overlay the main content by using setOverlayed method or umanoOverlay attribute. This is useful if you would like to make the sliding layout semi-transparent. You can also set umanoClipPanel to false to make the panel transparent in non-overlay mode.
  • By default, the main content is dimmed as the panel slides up. You can change the dim color by changing umanoFadeColor . Set it to «@android:color/transparent» to remove dimming completely.
Читайте также:  Notepad android без рекламы

Scrollable Sliding Views

If you have a scrollable view inside of the sliding panel, make sure to set umanoScrollableView attribute on the panel to supported nested scrolling. The panel supports ListView , ScrollView and RecyclerView out of the box, but you can add support for any type of a scrollable view by setting a custom ScrollableViewHelper . Here is an example for NestedScrollView

Once you define your helper, you can set it using setScrollableViewHelper on the sliding panel.

This library was initially based on the opened-sourced SlidingPaneLayout component from the r13 of the Android Support Library. Thanks Android team!

Tested on Android 2.2+

  • Nov 23, 15 — @kiyeonk — umanoScrollInterpolator support
  • Jan 21, 14 — ChaYoung You (@yous) — Slide from the top support
  • Aug 20, 13 — @gipi — Android Studio Support
  • Jul 24, 13 — Philip Schiffer (@hameno) — Maven Support
  • Oct 20, 13 — Irina Preșa (@iriina) — Anchor Support
  • Dec 1, 13 — (@youchy) — XML Attributes Support
  • Dec 22, 13 — Vladimir Mironov (@MironovNsk) — Custom Expanded Panel Height

If you have an awesome pull request, send it over!

  • 3.4.0
    • Use the latest support library 26 and update the min version to 14.
    • Bug fixes
  • 3.3.1
    • Lots of bug fixes from various pull requests.
    • Removed the nineoldandroids dependency. Use ViewCompat instead.
  • 3.3.0
    • You can now set a FadeOnClickListener , for when the faded area of the main content is clicked.
    • PanelSlideListener has a new format (multiple of them can be set now
    • Fixed the setTouchEnabled bug
  • 3.2.1
    • Add support for umanoScrollInterpolator
    • Add support for percentage-based sliding panel height using layout_weight attribute
    • Add ScrollableViewHelper to allow users extend support for new types of scrollable views.
  • 3.2.0
    • Rename umanoParalaxOffset to umanoParallaxOffset
    • RecyclerView support.
  • 3.1.0
    • Added umanoScrollableView to supported nested scrolling in children (only ScrollView and ListView are supported for now)
  • 3.0.0
    • Added umano prefix for all attributes
    • Added clipPanel attribute for supporting transparent panels in non-overlay mode.
    • setEnabled(false) — now completely disables the sliding panel (touch and programmatic sliding)
    • setTouchEnabled(false) — disables panel’s touch responsiveness (drag and click), you can still control the panel programatically
    • getPanelState — is now the only method to get the current panel state
    • setPanelState — is now the only method to modify the panel state from code
  • 2.0.2 — Allow wrap_content for sliding view height attribute. Bug fixes.
  • 2.0.1 — Bug fixes.
  • 2.0.0 — Cleaned up various public method calls. Added animated showPanel / hidePanel methods.
  • 1.0.1 — Initial Release

Licensed under the Apache License, Version 2.0 (the «License»); you may not use this work except in compliance with the License. You may obtain a copy of the License in the LICENSE file, or at:

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an «AS IS» BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Читайте также:  Acer a500 android 4 глюки

About

This library provides a simple way to add a draggable sliding up panel (popularized by Google Music and Google Maps) to your Android application. Brought to you by Umano.

Источник

how to use android sliding up panel

I have downloaded the umano sliding up panel from https://github.com/umano/AndroidSlidingUpPanel

Imported it into the workspace and added reference to it in my project.

Next I copied and pasted the following into a new layout —

Here is the Code :

But I am getting an error unbound prefix.

What is wrong in my code?

And How can i fix this ?

5 Answers 5

You are missing namespace for android

So it should be

considering you have custom attributes

Looks like you are using

Its a library project and you must reference it in your andorid project. Scodnly missing android namespace as mentioned. The below should fix it

You can use BottomSheetBehavior from android support library from google as alternative. compile ‘com.android.support:design:25.0.0’ You can checkout my sample https://github.com/andrisasuke/Android-SlidingUp-Panel

I also implemented a SlidingUpPaneLayout, based on the SlidingPaneLayout, but the slide direction is vertical you can slide up and down for the top view, it’s more simple,just two views and no more attribute need to set.see at github,https://github.com/chenjishi/SlidingUpPaneLayout

If you want to slide your main body along with sliding part then only then add umanoParallaxOffset attribute otherwise remove it

Don’t forget it! sothree:umanoOverlay=»true»

you are getting unbound prefix error means you are done with referencing the library, you just need to modify xmlns attributes and make the slidingUpPanelLayout the root and you are done. dont’t forgot to change «com.example.slidinguppanel» with your package name. Hope it will fix your problem.

Not the answer you’re looking for? Browse other questions tagged android or ask your own question.

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.12.3.40888

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Оцените статью