- How to wrap height of Android ViewPager2 to height of current item? #184
- Comments
- sindicly commented Sep 9, 2020
- sindicly commented Sep 9, 2020
- This is the layout:
- The following is the method I used before, but it doesn’t work
- sindicly commented Sep 9, 2020
- CodeK1988 commented Oct 28, 2020
- hadia commented Jan 2, 2021
- yinxiucheng commented Jan 12, 2021
- yinxiucheng commented Jan 12, 2021
- JiaYuZ commented Jan 21, 2021 •
- ChinGyi2019 commented Feb 2, 2021 •
- hereisderek commented Mar 4, 2021 •
- whatiamdoing commented Jun 11, 2021
- MohammadRezaei92 commented Jun 19, 2021 •
- Ikrimah1998 commented Jun 21, 2021
- Ikrimah1998 commented Jun 21, 2021
- MohammadRezaei92 commented Jun 23, 2021
- Ikrimah1998 commented Jun 24, 2021
- MohammadRezaei92 commented Jun 24, 2021
- Ikrimah1998 commented Jun 24, 2021
- letsky commented Jul 7, 2021 •
- Ikrimah1998 commented Jul 7, 2021
- adherencegoo commented Jul 16, 2021
- sdzshn3 commented Aug 11, 2021 •
- MarkWang33 commented Oct 18, 2021
- Как работать с ViewPager2
- Новые фичи
- Что изменилось?
- Добавление зависимости
- Настройка
- Вертикальная прокрутка
- Использование FragmentStateAdapter
- Улучшенный OnPageChangeCallback
- Внимание!
- ViewPager2 с различной высотой элемента и WRAP_CONTENT
- Например. скажем у меня есть два взгляда:
- 3 ответа
- ViewPager with FragmentPagerAdapter
How to wrap height of Android ViewPager2 to height of current item? #184
Comments
sindicly commented Sep 9, 2020
The content of each piece of mine is long and short. How can I make viewpager2 fit the height of the subview?
The text was updated successfully, but these errors were encountered:
sindicly commented Sep 9, 2020
This is the layout:
The following is the method I used before, but it doesn’t work
`mViewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() <
@OverRide
public void onPageSelected(int position) <
super.onPageSelected(position);
/* View childView = mViewPager.getChildAt(position);
View rootView = mViewPager.getRootView();*/
sindicly commented Sep 9, 2020
Why can’t viewpager2 be inherited without openness at all
CodeK1988 commented Oct 28, 2020
dataBinding.viewPager2.registerOnPageChangeCallback(object :
ViewPager2.OnPageChangeCallback() <
override fun onPageScrolled(
position: Int,
positionOffset: Float,
positionOffsetPixels: Int
) <
super.onPageScrolled(position, positionOffset, positionOffsetPixels)
if (position > 0 && positionOffset == 0.0f && positionOffsetPixels == 0) <
dataBinding.viewPager2.layoutParams.height =
dataBinding.viewPager2.getChildAt(0).height
>
>
>). try it
hadia commented Jan 2, 2021
any luck for solving the issue
yinxiucheng commented Jan 12, 2021
@hadia could you paste the code of solving.
yinxiucheng commented Jan 12, 2021
JiaYuZ commented Jan 21, 2021 •
I’ve implemented the viewPager2.registerOnPageChangeCallback and added listener in viewpager2’s fragment, after data loaded completed and UI render completed, ask the surveyViewPager to reset height again
It solve the problem
ChinGyi2019 commented Feb 2, 2021 •
I’ve implemented the viewPager2.registerOnPageChangeCallback and added listener in viewpager2’s fragment, after data loaded completed and UI render completed, ask the surveyViewPager to reset height again
It solve the problem
if u mind, show me some light plexx
.
hereisderek commented Mar 4, 2021 •
this is for wrapping the height of each view
whatiamdoing commented Jun 11, 2021
MohammadRezaei92 commented Jun 19, 2021 •
this is for wrapping the height of each view
I do some improvements on it to change the height of viewpager if view height changes on runtime:
Ikrimah1998 commented Jun 21, 2021
how do i implement ViewPager2ViewHeightAnimator ?
Ikrimah1998 commented Jun 21, 2021
this is for wrapping the height of each view
I do some improvements on it to change the height of viewpager if view height changes on runtime:
How do i Implement this?
MohammadRezaei92 commented Jun 23, 2021
how do i implement ViewPager2ViewHeightAnimator ?
1 Copy this class to your project.
2 Get an instance of it.
3 Pass your viewpager to viewpager2 variable.
Ikrimah1998 commented Jun 24, 2021
how do i implement ViewPager2ViewHeightAnimator ?
1 Copy this class to your project.
2 Get an instance of it.
3 Pass your viewpager to viewpager2 variable.
Get an instance? how
MohammadRezaei92 commented Jun 24, 2021
how do i implement ViewPager2ViewHeightAnimator ?
1 Copy this class to your project.
2 Get an instance of it.
3 Pass your viewpager to viewpager2 variable.
Get an instance? how
Do you know programming at all?
Ikrimah1998 commented Jun 24, 2021
how do i implement ViewPager2ViewHeightAnimator ?
1 Copy this class to your project.
2 Get an instance of it.
3 Pass your viewpager to viewpager2 variable.
Get an instance? how
Do you know programming at all?
Noo, please can i see the code
letsky commented Jul 7, 2021 •
how do i implement ViewPager2ViewHeightAnimator ?
1 Copy this class to your project.
2 Get an instance of it.
3 Pass your viewpager to viewpager2 variable.
Get an instance? how
Do you know programming at all?
Noo, please can i see the code
use findViewById() get your ViewPager2 instance
Ikrimah1998 commented Jul 7, 2021
how do i implement ViewPager2ViewHeightAnimator ?
1 Copy this class to your project.
2 Get an instance of it.
3 Pass your viewpager to viewpager2 variable.
Get an instance? how
Do you know programming at all?
Noo, please can i see the code
use findViewById() get your ViewPager2 instance
how to i Pass your viewpager to viewpager2 variable.?
adherencegoo commented Jul 16, 2021
this is for wrapping the height of each view
I do some improvements on it to change the height of viewpager if view height changes on runtime:
I encountered a bug when applying this solution: the first fragment in viewPager2 is always match_parent when just entering the page
And, I solved it by making OnGlobalLayoutListener disposable
- Add an extension for convenience
sdzshn3 commented Aug 11, 2021 •
Try this. This is working very well
Put this in the fragment which is being used in viewPager
MarkWang33 commented Oct 18, 2021
Thanks guys for help this problem.
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Источник
Как работать с ViewPager2
Прошло не так много времени с тех пор, как 7 февраля 2019 года Google выпустила альфа-версию Android ViewPager2. Более подробную информацию об этом релизе можно найти здесь. А сейчас давайте посмотрим, что из себя представляет ViewPager2.
Новые фичи
Что изменилось?
ViewPager2 выпущен для Android X, поэтому, если вы хотите его использовать, ваш проект должен использовать Android X. Давайте посмотрим, как мы можем использовать этот новый ViewPager2.
Добавление зависимости
Добавьте следующую зависимость в файл build.gradle на уровне приложения:
После этого синхронизируйте свой проект.
Настройка
Добавьте виджет ViewPager2 в вашу Activity или фрагмент:
Давайте создадим layout для страницы, которая будет отображаться во ViewPager2:
Далее нам нужно создать Adapter для ViewPager2. Это самая интересное. Для этого мы можем использовать RecyclerView.Adapter . Разве это не круто?
Это такой же адаптер, который мы используем для обычного RecyclerView, и с ViewPager2 он работает так же хорошо.
Последний шаг, установим адаптер для ViewPager2:
Вот и всё! Получаем тот же результат, как и при использовании старого ViewPager с PagerAdapter:
Вертикальная прокрутка
Раньше нужно было использовать сторонние библиотеки для реализации вертикальной прокрутки, т.к. до сих пор Google не предоставляла такой возможности «из коробки». В этом новом ViewPager2 теперь есть поддержка вертикальной прокрутки. Просто измените ориентацию во ViewPager2 и вертикальная прокрутка будет включена. Очень просто!
Вот, что получается в итоге:
Использование FragmentStateAdapter
Вы также можете использовать фрагменты в качестве страниц, как и в старом ViewPager. Для этого есть FragmentStateAdapter. Давайте посмотрим, как мы можем его использовать.
Прежде всего, нам нужно создать фрагмент:
Теперь мы создадим адаптер для ViewPager2. В его конструктор мы передадим FragmentManager, который будет управлять фрагментами:
Теперь установим этот новый адаптер во ViewPager2, и всё готово:
Улучшенный OnPageChangeCallback
В старом ViewPager интерфейс OnPageChangeListner был предназначен для получения событий изменения/прокрутки страницы. И это была очень неудобно, т.к. нам нужно было переопределять все три метода ( onPageScrollStateChanged , onPageScrolled , onPageSelected ), даже если мы этого не хотели.
Теперь у нас есть OnPageChangeCallback , абстрактный класс с неабстрактными методами. Что буквально означает, что нам не нужно переопределять все эти методы, мы можем просто переопределить те, которые нам нужны или которые мы хотим использовать. Вот так, например, мы можем отслеживать события смены страницы:
Внимание!
Поскольку ViewPager2 находится в альфа-версии, есть некоторые функции старого ViewPager, которые ещё не были реализованы или не работают должным образом в этой версии.
Известные проблемы согласно документации:
- ClipToPadding,
- Отсутствует интеграция с TabLayout,
- Отсутствует контроль за пределами экрана,
- Нельзя установить ширину страницы (100% по умолчанию)
Больше информации об известных проблемах — здесь. Надеюсь, что всё это будет исправлено в ближайших обновлениях. Я с нетерпением жду стабильной версии этого нового ViewPager2. А до тех пор, хорошего всем кода!
Источник
ViewPager2 с различной высотой элемента и WRAP_CONTENT
Есть несколько сообщений о том, как заставить ViewPager работать с элементами разной высоты, которые сосредоточены вокруг расширения ViewPager , чтобы изменить его onMeasure для поддержки этого.
Однако, учитывая, что ViewPager2 помечен как финальный класс, расширение его — это не то, что мы можем сделать.
Кто-нибудь знает, есть ли способ сделать это?
Например. скажем у меня есть два взгляда:
Когда ViewPager2 ( layout_height=»wrap_content» ) загружается — смотря на View1, его высота будет 200dp.
Но когда я прокручиваю до View2, высота все равно 200dp; последние 100dp View2 обрезаны.
3 ответа
Решение состоит в том, чтобы зарегистрировать PageChangeCallback и отрегулировать LayoutParams ViewPager2 после того, как ребенок попросит повторно измерить себя.
В качестве альтернативы, если высота вашего вида может измениться в какой-то момент из-за, например, асинхронная загрузка данных, затем используйте вместо этого прослушиватель глобальной компоновки:
Смотрите обсуждение здесь:
Наткнулся на это дело сам однако с фрагментами. Вместо того, чтобы изменить размер представления как принятого ответа, я решил обернуть представление в ConstraintLayout. Для этого необходимо указать размер вашего ViewPager2 и не использовать wrap_content.
Таким образом, вместо изменения размера нашего окна просмотра, он должен быть минимальным размером самого большого представления, которое он обрабатывает.
Немного новичок в Android, поэтому не знаю, хорошее ли это решение или нет, но оно мне подходит.
Источник
ViewPager with FragmentPagerAdapter
Layout that allows the user to swipe left and right through «pages» of content which are usually different fragments. This is a common navigation mode to use instead of ActionBar Tabs with Fragments.
A ViewPager is a layout which can be added to any layout XML file inside a root layout:
If you want an «indicator» that displays the pages available at the top as shown in the screenshot above, you need to include a nested indicator view called a PagerTabStrip:
which will automatically display the page indicator for your pager. You might want to check out the popular ViewPagerIndicator for an improved page indicator.
Next, let’s suppose we have defined two fragments FirstFragment and SecondFragment both of which contain a label in the layout and have implementations such as:
Now we need to define the adapter that will properly determine how many pages exist and which fragment to display for each page of the adapter by creating a FragmentPagerAdapter:
For more complex cases with many pages, check out the more dynamic approach with SmartFragmentStatePagerAdapter explained later.
Finally, let’s associate the ViewPager with a new instance of our adapter:
And now we have a basic functioning ViewPager with any number of fragments as pages which can be swiped between.
We can access the selected page within the ViewPager at any time with the getCurrentItem method which returns the current page:
The current page can also be changed programmatically with the
With this getter and setter, we can easily access or modify the selected page at runtime.
If the Activity needs to be able listen for changes to the page selected or other events surrounding the ViewPager , then we just need to hook into the ViewPager.OnPageChangeListener on the ViewPager to handle the events:
We can use the ViewPager to display a tabbed indicator in order to create tabs to display our fragments. At Google I/O 2015, Google announced a new TabLayout class that makes creating this tabbed interface fairly easy to do. See Google Play Style Tabs using TabLayout for a walkthrough.
An alternative approach to achieve this is to use the third-party PagerSlidingTabStrip library.
In this way, we can use the same pager system described above and augment the pager with a tabbed navigation indicator.
In certain cases, we may require a dynamic ViewPager where we want to get access to fragment instances or with pages being added or removed at runtime. If your ViewPager is more dynamic with many pages and fragments, we will want to use an implementation of the alternate FragmentStatePagerAdapter instead. Below shows us how to use this and also intelligently cache the fragments for easy lookup.
First, copy in the SmartFragmentStatePagerAdapter.java which provides the intelligent caching of registered fragments within our ViewPager . It does so by overriding the instantiateItem() method and caching any created fragments internally. This solves the common problem of needing to access the current item within the ViewPager.
Now, we want to extend from SmartFragmentStatePagerAdapter copied above when declaring our adapter so we can take advantage of the better memory management of the state pager:
Now with this adapter in place, we can also easily access any fragments within the ViewPager with:
and we can easily access the «current» pager item with:
This pattern should save your app quite a deal of memory and allow for much easier management of fragments within your pager for the right situation.
In certain cases, we want to dynamically replace the Fragment shown for a given page within a ViewPager . For example, perhaps the page in the ViewPager currently displays a list of items and we want to have a detail view show up when an item is selected. There are two approaches for this: create a fragment container as a page or switch fragments from within the adapter.
The first approach is to have the page display a fragment container that switches between multiple child content fragments as outlined in this tutorial on the subject. You can view the working sample code here as well.
The second approach is to switch the fragment that displays inside the FragmentPagerAdapter by overriding the getItem(. ) method as well as getItemPosition(Object object) which is invoked every time you call viewPager.getAdapter().notifyDataSetChanged() . For example:
You would then invoke notifyDataSetChanged on the pager adapter to trigger a reload of the pager at any time. For more details, check out this StackOverflow thread as well as this post.
Alternatively, you can use the method setOffscreenPageLimit(int limit) provided by ViewPager to set how many page instances you want the system to keep in memory on either side of your current page. As a result, more memory will be consumed. So be careful when tweaking this setting if your pages have complex layouts.
For example, to let the system keep 3 page instances on both sides of the current page:
This can be useful in order to preload more fragments for a smoother viewing experience trading off with memory usage.
If you are interested in a ViewPager with visible adjacent pages that are partially visible:
We can do that with by tuning a few properties of our pager. First, here’s how the ViewPager might be defined in the XML Layout:
Next, we need to tune these properties of the pager in the containing fragment or activity:
Finally we need to adjust the width inside the adapter:
For more details, you can follow these guides:
We can customize how the pages animate as they are being swiped between using the PageTransformer.
The easiest way to leverage transformers is to use this ViewPagerTransforms library:
Loading the library into app/build.gradle with:
and then using the desired effect:
Other transform types include AccordionTransformer , CubeInTransformer , FlipHorizontalTransformer , ScaleInOutTransformer , ZoomInTransformer , and many others.
However, custom usage is pretty straightforward, just attach a PageTransformer to the ViewPager:
The first argument is set to true if the supplied PageTransformer requires page views to be drawn from last to first instead of first to last. The second argument is the transformer which requires defining the transformPage method to define the sliding page behavior.
The transformPage method accepts two parameters: page which is the particular page to be modified and position which indicates where a given page is located relative to the center of the screen. The page which fills the screen is at position 0. The page immediately to the right is at position 1. If the user scrolls halfway between pages one and two, page one has a position of -0.5 and page two has a position of 0.5.
For more details, check out the official guide or this guide. You can also review this cool rotating page transformer effect for another example.
If we want to disable swipe in a particular direction, check out this custom ViewPager that swipes in only one direction using a custom class extending ViewPager that intercepts the swipe touch events.
In certain situations your app might even want to have a ViewPager that allows switching pages using an indicator but that doesn’t intercept swipe events at all. This is usually because we want to have the swipe events perform another action rather than change the page.
The first step is to define a custom ViewPager subclass called LockableViewPager. The class inherits from ViewPager and includes a new method called setSwipeable to control if swipe events are enabled or not. Copy this class into your project. Make sure to change your layout file accordingly:
Now, just call setSwipeable(false) to disable swiping to change the page.
Often when launching a tabbed activity, there needs to be a way to select a particular tab to be displayed once the activity loads. For example, an activity has three tabs with one tab being a list of created posts. After a user creates a post on a separate activity, the user needs to be returned to the main activity with the «new posts» tab displayed. This can be done through the use of intent extras and the ViewPager#setCurrentItem method. First, when launching the tabbed activity, we need to pass in the selected tab as an extra:
If the activity needs to return a result, we can also return this as an activity result. Next, we can read this information from the intent within the tabbed activity:
With that, any activity can launch the tabbed activity with the ability to configure the selected tab.
While a ViewPager is often coupled with a Fragment for each page using the FragmentPagerAdapter , there are cases where the pages are better off as plain views.
A good example is an image gallery, where the user can swipe between different pictures. To achieve this, we can extend from PagerAdapter :
This is most commonly used for image slideshows or galleries. See this image gallery tutorial or this viewpager without fragments guide for more detailed steps.
An «indicator» is the UI element that displays the possible pages and the current page such as «tabs». There are a number of other custom indicators for the pager that can be helpful in various contexts.
A few of the most interesting ones are listed below:
- Spring indicator with animated elastic selection. Indicator that visually springs between pages as dragged.
- Simple circle «dots» indicator for pages. Indicator that displays the typical «dots» associated to pages.
- Custom «Ink» dots indicator for pages. Indicator that displays dots for items and uses «ink» to visualize the current page.
Источник