- Tek Eye
- Determining the Size of an Android View or Screen at Run Time
- Finding the Size of an Android View in Code
- Finding the Size of an Android Layout in Code
- Finding the Size of an Android View During Screen Construction
- See Also
- Archived Comments
- Do you have a question or comment about this article?
- mstfldmr / CameraPreview.java
- Как получить размер экрана Android в программном отношении, раз и навсегда?
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:
Источник
mstfldmr / CameraPreview.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
package net.aldemir.myapp.camera ; |
import android.content.Context ; |
import android.content.res.Configuration ; |
import android.graphics.Point ; |
import android.hardware.Camera ; |
import android.os.Handler ; |
import android.util.AttributeSet ; |
import android.util.Log ; |
import android.view.Display ; |
import android.view.Surface ; |
import android.view.SurfaceHolder ; |
import android.view.SurfaceView ; |
import android.view.ViewGroup ; |
import android.view.WindowManager ; |
import java.util.List ; |
public class CameraPreview extends SurfaceView implements SurfaceHolder . Callback < |
public int getDisplaySize () < |
WindowManager wm = ( WindowManager ) getContext() . getSystemService( Context . WINDOW_SERVICE ); |
Display display = wm . getDefaultDisplay(); |
Point size = new Point (); |
display . getSize(size); |
int width = size . x; |
int height = size . y; |
> |
> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
package net.aldemir.myapp.gui.activity ; |
import android.graphics.Point ; |
import android.os.Bundle ; |
import android.view.Display ; |
import at.ingdiba.ingdibaapp.R ; |
import at.ingdiba.ingdibaapp.gui.activity.base.BaseActionBarActivity ; |
public class MyActivity extends BaseActionBarActivity < |
@Override |
public void onCreate ( Bundle state ) < |
super . onCreate(state); |
setContentView( R . layout . activity_barcode_reader); |
Display display = getWindowManager() . getDefaultDisplay(); |
Point size = new Point (); |
display . getSize(size); |
int width = size . x; |
int height = size . y; |
> |
> |
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.
Источник
Как получить размер экрана Android в программном отношении, раз и навсегда?
Как я могу определить размер экрана программно, в единицах, используемых событиями касания и Просмотр измерения / макета? Другими словами, мне нужны координаты нижнего правого угла экрана, в системе координат, используемой сенсорными событиями getRawX()/getRawY() и View.getLocationOnScreen() .
Я не решаюсь называть нужные пиксели «событий» событий / просмотров, поскольку, по-видимому, в моем телефоне существует несколько понятий «пикселей», и они не дополняют последовательную историю.
Я вижу, что это было спрошено и много ответили на stackoverflow и в других местах, но ни один из ответов не работает на моем телефоне (droid 4, android 4.1.2) во всех режимах:
- Могу ли я узнать ширину экрана программно в приложении Android?
- Как я могу получить ScreenSize программно в android
- Android set Просмотр видимости программно на основе размера экрана
- Как получить высоту экрана в Android?
- Получить высоту экрана в Android
- https://groups.google.com/forum/#!topic/android-developers/IpxnfvDFrpc
- http://shuklaxyz.blogspot.com/2012/02/how-to-programmatically-figure-out.html
- http://coderock.net/how-to-determine-screen-resolution-programmatically/
- http://www.codeproject.com/Tips/313848/Get-actual-screen-size-for-the-application-layout
- Android и настройка ширины и высоты программно в единицах dp
- http://www.simplecodestuffs.com/how-to-get-screen-dimensions-programmatically-in-android/
- http://www.androidsnippets.com/get-size-and-orientation-of-the-screen
- http://grokbase.com/t/gg/android-developers/127aatfqb6/how-to-determine-screen-resolution-programmatically
Это код библиотеки, который должен работать независимо от того, находится ли приложение в режиме совместимости с экраном (т.е. targetSdkVersion
Мой телефон (дроид 4 работает андроид 4.1.2) имеет 540×960 физических пикселей, то есть маленькие цветные светящиеся точки.
Размер экрана в желаемых единицах, от просмотра событий касания и просмотра измерений, составляет 360×640, когда приложение находится в режиме сопоставления экрана, 540×960, когда приложение не находится в режиме сопоставления экрана. Это номера, которые мне нужно найти программно, без проблем с сенсорными событиями или представлениями, чтобы найти их, но мне очень трудно найти какой-либо API, который вернет эти числа.
Объекты Display и DisplayMetrics, полученные разными способами, требуют, чтобы размер экрана составлял 540×960 «пикселей» (независимо от того, включен режим экрана или нет). Чтобы быть конкретным, все говорят, что все 540×960 все время: DisplayMetrics.
Конфигурационные объекты, полученные разными способами, говорят на экране <Ширина, Высота>Dp = 360×614 (независимо от того, включен режим экрана или нет). Я не считаю, что это весь экран, так как соотношение сторон неверно. (Я думаю, что это весь экран минус строка состояния, мне нужен весь экран.) Я думаю, можно с уверенностью сказать, что весь экран 360×640 dp, хотя я не знаю API, который возвращает этот 640.
DisplayMetrics, полученный разными способами, говорит, что «плотность» равна 1.0f, когда в режиме сопоставления экрана, 1.5f, если не в режиме сопоставления экрана.
Функция getWindow().getAttributes().
Я понимаю, что предполагается следующая формула: pixels = dp * density. Кажется, что она согласуется со всеми зарегистрированными номерами ((3), (4), (5) выше), если не в режиме совместимости экрана: 540×960 = 360×640 * 1,5 Но в режиме совместимости с экраном он не складывается: 540×960! = 360×640 * 1 Итак, что-то не так.
Самое простое объяснение, я думаю, в том, что методы, перечисленные в (3) выше, просто дают неправильный ответ для «пикселей», когда в режиме сопоставления экрана – то есть они должны были возвращать 360 × 640 «пикселей», но они ошибочно Возвращая 540×960 вместо этого. Но могут быть и другие способы взглянуть на это.
В любом случае получение желаемых номеров независимо от режима, из вышеупомянутых частей головоломки, безусловно, является сложной загадкой. Я нашел способ, который, кажется, работает на моем телефоне в обоих режимах, но он чрезвычайно обходчив, и он полагается на два предположения, которые все еще кажутся довольно шаткими (как описано в комментариях к коду ниже).
Есть ли лучший / более чистый способ найти размер экрана?
Теперь вы можете измерить размер экрана в пикселях, который является лучшим единицей измерения, чем сантиметр, потому что все кнопки, текстовые изображения и т. Д. Измеряются в этом устройстве. То, что я обычно использую
Используя DisplayMetrics, вы можете получить высоту и ширину экрана любого устройства. Вот код.
В вашем методе onCreate
В своем # 6 вы отмечаете, что DecorView, похоже, обеспечивает то, что вы хотите, но вы не думаете, что это реально. Я считаю, что это так близко, как вы можете прийти. Согласно документации для Window.getDecorView :
Извлеките представление окна верхнего уровня окна (содержащее стандартный оконный фрейм / декорации и содержимое клиента внутри него), который можно добавить в окно окна в оконный менеджер.
Строка состояния является частью упомянутого там оформления окна. Программные клавиатуры и другие наложения получат свое собственное окно, поэтому они не должны мешать соответствующим значениям. Правильно, что это не точно показатели отображения, но если ваше приложение полноэкранное, всегда должен быть полный размер экрана, отфильтрованный через переводчик совместимости. Другие приложения не будут иметь доступ к Window вашего приложения, поэтому нет необходимости беспокоиться о том, что какое-либо другое приложение меняет атрибуты, пока вы не смотрите.
Надеюсь, это поможет.
Если вы используете уровень api 17 или выше, проверьте getRealMetrics и getRealSize на дисплее
Для уровня api 14,15 & 16 смотрите здесь
Я должен поставить это как комментарий, но у меня нет репутации для этого.
Это может быть не совсем правильный ответ, но я получил свои размеры, когда я переключил высоту и ширину в методе DisplayMetrics.
Как я сказал, это может быть неверно, но я не знаю, почему, но это сработало для меня.
Я использовал теорему Пифагора, чтобы найти диагональный размер экрана телефона Android / планшета Android, тот же самый принцип можно применить к экрану iPhone или Blackberry.
Пифагор, должно быть, был гением, он знал программирование смартфонов так много лет назад: p
Я использую метод ниже, чтобы получить ширину устройства:
Я думаю, что эта функция поможет вам просто получить ширину и высоту размера экрана вашего андроида. Функция возвращает ширину и высоту в виде массива целых чисел, как показано ниже
И на вашем методе создания выведите свою ширину и высоту, как показано ниже.
Загрузите исходный код и протестируйте его на своей студии Android.
Источник