Android get view height

Tek Eye

For efficient bitmap handling or dynamic View creation in an app, the area that a screen item or layout is using needs to be known. If no fixed sizes are allocated at design time the size of a View may not be known until an app is executed. This is because of the wide range of display sizes that Android supports. Just look on GSMArena to see the huge range of Android devices produced over the years, and to see the wide variation in screen sizes and pixel densities. The example code in this article shows how to read the screen size and the size of Views as the app runs.

(Note: All Android screen items are derived from Views. A screen component, e.g. a TextView , is derived from the View class. Such screen components are also known as widgets. Layouts are ViewGroups and are also derived from Views.)

Determining the Size of an Android View or Screen at Run Time

To run the example code in this article first create a new Android project. Those new to Android programming can read the article Your First Android Hello World Java Program to see how. For this article the app is called View Size.

Use a simple layout for activity_main.xml (the layout file may have another name). Add a TextView with id labXY and set the Text attribute to X,Y. Next to it add another TextView called textXY with Text set to ? (actually \? to make it valid in the XML). Here is the layout used for this example:

Add this code to the bottom of the onCreate method in MainActivity.java (or whatever the class was called). Add the required an imports for TextView and DisplayMetrics when prompted with the Alt-Enter:

This is the code running on an Android Virtual Device (AVD) with a 320×480 screen:

Finding the Size of an Android View in Code

Drop an ImageView onto the layout, here using the ic_launcher.png icon file, or other images can be used. The size of a View can be retrieved using the getWidth and getHeight methods. Change the code in the onCreate to set the TextView to the ImageView’s width and height (an import for View is required, again usually prompted for and added with Alt-Enter):

Читайте также:  Видеорегистратор для андроид без рекламы

Mmmmm! The code is showing 0,0 for the ImageView size, even though we can see that it is not 0,0:

This is because in onCreate the screen has not yet been laid out so the size of the ImageView has not been determined hence the getWidth() and getHeight() methods are returning zero. In fact they will likely return zero in onStart() and onResume(). What is needed is to override onWindowFocusChanged() to get the ImageView sizes:

Finding the Size of an Android Layout in Code

The same code can be used to get the size of the View (the layout, i.e. ViewGroup) in which the screen components sit. Notice that in the screen XML the RelativeLayout was given an id (@+id/screen), which means the base View’s width and height can be grabbed (change R.id.imageView to R.id.screen in the code):

Notice that the layout height is less than the screen height because of the notification bar.

Finding the Size of an Android View During Screen Construction

To get the the size of a View as soon as it is known (rather than waiting for the onWindowFocusChanged event) attach a listener to its ViewTreeObserver . Do this by writing a class that implements ViewTreeObserver.OnGlobalLayoutListener in the Activity’s class. This new class will have an onGlobalLayout method that gets the View dimensions that can then be stored for later use (here they are displayed as before). Here is the example source code for the entire MainActivity.java file to show this way of getting the ImageView’s width and height:

Download some example code in view-size.zip from this article, ready for importing into Android Studio. See the instructions in the zip file, alternatively the code can also be accessed via the Android Example Projects page.

See Also

  • Using Immersive Full-Screen Mode on Android Developers
  • See the Android Example Projects page for lots of Android sample projects with source code.
  • For a full list of all the articles in Tek Eye see the full site alphabetical Index.

Archived Comments

Kestrel on December 15, 2014 at 4:20 am said: Hey fantastic article, can you also talk about the fitSystemWindows and how things are affected when its set or not set by default. Thanks in advance.

Author: Daniel S. Fowler Published: 2013-06-19 Updated: 2017-12-17

Do you have a question or comment about this article?

(Alternatively, use the email address at the bottom of the web page.)

↓markdown↓ CMS is fast and simple. Build websites quickly and publish easily. For beginner to expert.

Free Android Projects and Samples:

Источник

Определение размера представления Android во время выполнения

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

это кажется легкой задачей, и есть много так вопросов относительно этого, хотя никто что, очевидно, решило мою проблему. Так что, возможно, я упускаю что-то очевидное. Я получаю ручку к моему взгляду:

это работает нормально, но при вызове getWidth() , getHeight() , getMeasuredWidth() , getLayoutParams().width и т. д. все они возвращают 0. Я также попытался вручную позвонить measure() на вид с последующим вызовом getMeasuredWidth() , но это не имеет никакого эффекта.

Читайте также:  Sunrider academy для андроид

Я попытался вызвать эти методы и проверить объект в отладчике в моей деятельности onCreate() и onPostCreate() . Как может Я выясняю точные размеры этого представления во время выполнения?

10 ответов:

используйте ViewTreeObserver на представлении, чтобы дождаться первого макета. Только после того, как первый макет будет getWidth()/getHeight()/getMeasuredWidth()/getMeasuredHeight() работы.

Существует несколько решений, в зависимости от сценария:

  1. безопасный метод, будет работать непосредственно перед рисованием Вида, после завершения этапа компоновки:
  1. в некоторых случаях, достаточно измерить размер вручную:
  1. если у вас есть пользовательский вид, который вы расширили, вы можете получите его размер по методу «onMeasure», но я думаю, что он хорошо работает только в некоторых случаях:

если вы пишете в Kotlin, вы можете использовать следующую функцию, которая за кулисами работает точно так же, как runJustBeforeBeingDrawn что я написал:

обратите внимание, что вам нужно добавить это в gradle (найдено через здесь):

ты называешь getWidth() прежде чем вид на самом деле выложен на экране?

распространенной ошибкой новых разработчиков Android является использование ширины и высота вида внутри его конструктора. Когда представление конструктор называется, Android еще не знает, насколько большой вид будет быть, поэтому размеры установлены на ноль. Реальные размеры рассчитываются во время этап компоновки, который происходит после строительства, но перед чем-либо почерпнутый. Вы можете использовать onSizeChanged() метод уведомления значения, когда они известны, или вы можете использовать getWidth() и getHeight() методы позже, например в onDraw() метод.

на основе рекомендаций @mbaird, я нашел приемлемое решение путем создания подклассов ImageView класса и переопределение onLayout() . Затем я создал интерфейс наблюдателя, который моя активность реализовала и передала ссылку на себя классу, что позволило ему сообщить активность, когда она была фактически завершена.

Я не на 100% убежден, что это лучшее решение (поэтому я пока не отмечаю этот ответ как правильный), но он работает и согласно документации первый раз, когда можно найти фактический размер представления.

вот код для получения макета путем переопределения представления, если API

вы можете проверить этот вопрос. Вы можете использовать View ‘ s post () метод.

это работает для меня в моем onClickListener :

Я тоже потерялся вокруг getMeasuredWidth() и getMeasuredHeight() getHeight() и getWidth() в течение длительного времени. позже я обнаружил, что получение ширины и высоты в onSizeChanged() это лучший способ, чтобы сделать это. вы можете динамически получить текущую ширину и текущую высоту вашего представления, переопределив onSizeChanged( ) метод.

возможно, вы захотите взглянуть на это, у которого есть сложный фрагмент кода. Новое сообщение в блоге: Как получить размеры ширины и высоты customView (extends View) в Android http://syedrakibalhasan.blogspot.com/2011/02/how-to-get-width-and-height-dimensions.html

используйте ниже код, это дает размер представления.

Источник

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

  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

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.

Источник

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