Android viewpager dynamic height

Содержание
  1. How to create a dynamic height wrapping ViewPager with scroll view when images have variable heights on Android.
  2. This is a combination of multiple online sources in order to help others how to create a height wrapping dynamic ViewPager.
  3. How to wrap height of Android ViewPager2 to height of current item? #184
  4. Comments
  5. sindicly commented Sep 9, 2020
  6. sindicly commented Sep 9, 2020
  7. This is the layout:
  8. The following is the method I used before, but it doesn’t work
  9. sindicly commented Sep 9, 2020
  10. CodeK1988 commented Oct 28, 2020
  11. hadia commented Jan 2, 2021
  12. yinxiucheng commented Jan 12, 2021
  13. yinxiucheng commented Jan 12, 2021
  14. JiaYuZ commented Jan 21, 2021 •
  15. ChinGyi2019 commented Feb 2, 2021 •
  16. hereisderek commented Mar 4, 2021 •
  17. whatiamdoing commented Jun 11, 2021
  18. MohammadRezaei92 commented Jun 19, 2021 •
  19. Ikrimah1998 commented Jun 21, 2021
  20. Ikrimah1998 commented Jun 21, 2021
  21. MohammadRezaei92 commented Jun 23, 2021
  22. Ikrimah1998 commented Jun 24, 2021
  23. MohammadRezaei92 commented Jun 24, 2021
  24. Ikrimah1998 commented Jun 24, 2021
  25. letsky commented Jul 7, 2021 •
  26. Ikrimah1998 commented Jul 7, 2021
  27. adherencegoo commented Jul 16, 2021
  28. sdzshn3 commented Aug 11, 2021 •
  29. MarkWang33 commented Oct 18, 2021
  30. Как работать с ViewPager2
  31. Новые фичи
  32. Что изменилось?
  33. Добавление зависимости
  34. Настройка
  35. Вертикальная прокрутка
  36. Использование FragmentStateAdapter
  37. Улучшенный OnPageChangeCallback
  38. Внимание!
  39. Android ViewPager with WRAPCONTENT height
  40. APPROACH
  41. Leave a Comment Cancel Reply
  42. 27 comments

How to create a dynamic height wrapping ViewPager with scroll view when images have variable heights on Android.

May 25, 2020 · 2 min read

This is a combination of multiple online sources in order to help others how to create a height wrapping dynamic ViewPager.

While using various heights of images on a single view we found it a trouble to ensure the images are not stretched as well as shrink make sure that the view wraps around the images. This article helps achieve this goal.

Use this custom view pager widget class.

If you want to use your ViewPager inside scroll view with other contains which will shrink and expand dynamically as per the image size use this custom scroll view.

Now here is the way how you can use this custom widgets it in your design xml files.

Here i s the MainActivity Kotlin file inside which you can set the ViewPager adapter.

Note: If you want to use this ViewPager inside fragment instead of activity just change “ supportFragmentManager” to “childFragmentManager” into this code

Finally these are the ImageFragment Kotlin and XML files which we are using for the adapter inside ViewPager for displaying various images with variable heights

This is the result what you get in the end

Thanks a lot if you have any queries please fill free to ask in comment section.

Источник

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

Читайте также:  Ricochet infinity для android

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

  1. 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

Читайте также:  Можно ли удалять папку android data

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. А до тех пор, хорошего всем кода!

Источник

Android ViewPager with WRAPCONTENT height

Recently, while working with the ViewPager, I found out that sometimes the Android ViewPager with WRAPCONTENT height flag is not visible. The reason for this is perhaps that the wrap_content flag needed height from the child view and the child view height is still not known.

The best way to check this is to fix the height to some hardcoded value say “200dp” and check if the view is visible.

Читайте также:  Spmc для андроид настройка

Now if the view is visible and it gets your work done you don’t need to follow this blog anymore as you have achieved your purpose. But, if you still want to have a viewpager which has height set by the wrap_content flag in your XML file, then you should continue reading.

I believe that the purpose of this blog is very clear to you by now. So I will just come to the approach I have used.

APPROACH

  1. Create A custom View class that extends the View Pager class.(say WrapContentViewPager).
  2. Create default constructors for your class as in the View Pager class, so that you can directly call super with these and create a proper view for your custom view and use it in xml as easily as you would use the ViewPager tag for creating the viewpager view.
  3. Create a Function that will add a simple page Change listener to your custom view and then call this function in the default constructors you just created in above step.
  4. Override the onMeasure Method of the ViewPager class in your custom View class and get the child’s measured height and then set in the height params and call the super function.

Use of this class in your XML File:-

The Above code will just change the height of the Viepager as per the current child. but the main power of the viewPager is to prepare the view for the previous and next item as well so if you want you can get this also and this again is nothing but iterating the viewPager as per the child in the memory so we just need to have a for loop in onMeasure method of the viewPager and iterate each child View.

Use of this class in your XML File:-

That’s it, you can run this code and check it yourself.

Leave a Comment Cancel Reply

27 comments

Thanks for your concern but we never faced this kind of issue in any of our apps.

The reason for your issues most probably is that you must have overridden the onResume() method of your activity. If that’s the case then you need to explicitly set up the view page and adapter again in onResume() method in order to avoid this issue.

If your problem is not solved with this approach, then please share your code and i will look into it.

can you provide your source code, so that we can have a look into your code and predict how this can be done?

Generally, if this kind of complex layout architecture is followed then you might have to maintain all the layouts (their width & height) in your view render(Activity/ Fragment) class.

Your code is working nice.

If I use this code in my app which is commercial,
Do I consider any license?

Thanks for the appreciating words.

No, this particular piece of information is not under any license.

You can use it anywhere you want.

Personally, I have not used the ViewPager2 till now.
But if something similar is troubling you then just make WrapContentViewPager extend ViewPager2, and then in the remaining article replace all the accourences of the view pager with viewPager2 and this should work.

If this does not works out, then please do share teh exact code with me, so that we can look and update you accordingly.

If this is already there, then we will need to have a look in your exact code.

Источник

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