Получить размеры экрана java android

How to Get View Size in Android

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:

Читайте также:  Команды ввода вывода python

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:

//object to store display information DisplayMetrics metrics = new DisplayMetrics(); //get display information getWindowManager().getDefaultDisplay().getMetrics(metrics); //show display width and height ((TextView)findViewById(R.id.textXY)).setText( Integer.toString(metrics.widthPixels)+","+Integer.toString(metrics.heightPixels));

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

Android Screen Size

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):

View v = (View) findViewById(R.id.imageView); String x = Integer.toString(v.getWidth()); String y = Integer.toString(v.getHeight()); //show ImageView width and height ((TextView)findViewById(R.id.textXY)).setText(x+","+y);

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

Incorrect Android View Size

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:

public void onWindowFocusChanged(boolean hasFocus)< super.onWindowFocusChanged(hasFocus); View v = (View) findViewById(R.id.imageView); String x = Integer.toString(v.getWidth()); String y = Integer.toString(v.getHeight()); //show ImageView width and height ((TextView)findViewById(R.id.textXY)).setText(x+","+y); >

The Correct Android View Size

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):

Android Layout Size

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:

package com.example.viewsize; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.view.ViewTreeObserver; import android.widget.ImageView; import android.widget.TextView; public class MainActivity extends AppCompatActivity < @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //Reference ImageView ImageView v = (ImageView) findViewById(R.id.imageView); //Attached a layout listener v.getViewTreeObserver().addOnGlobalLayoutListener(new MyGlobalListenerClass()); >//Declare the layout listener class MyGlobalListenerClass implements ViewTreeObserver.OnGlobalLayoutListener < @Override public void onGlobalLayout() < View v = (View) findViewById(R.id.imageView); String x = Integer.toString(v.getWidth()); String y = Integer.toString(v.getHeight()); //show ImageView width and height ((TextView)findViewById(R.id.textXY)).setText(x+","+y); >> >

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

ShareSubmit to TwitterSubmit to FacebookSubmit to LinkedInSubmit to redditPrint Page

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:

Источник

How can I get android device screen height, width?

This example demonstrates how do I get android device screen height, width.

Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.

Step 2 − Add the following code to res/layout/activity_main.xml.

Step 3 − Add the following code to src/MainActivity.java

import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.DisplayMetrics; import android.widget.TextView; public class MainActivity extends AppCompatActivity < TextView height, width, inches; DisplayMetrics displayMetrics; @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); height = findViewById(R.id.getScreenHeight); width = findViewById(R.id.getScreenWidth); inches = findViewById(R.id.getScreenInches); displayMetrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(displayMetrics); int screenHeight = displayMetrics.heightPixels; int screenWidth = displayMetrics.widthPixels; double y = Math.pow(screenHeight /displayMetrics.xdpi, 2); double x = Math.pow(screenWidth /displayMetrics.xdpi, 2); double screenInches = Math.sqrt(x + y); screenInches = (double) Math.round(screenInches *10)/10; height.setText("Screen Height: " + screenHeight); width.setText("Screen Height: " + screenWidth); inches.setText("Screen Inches: " + screenInches); >>

Step 4 − Add the following code to androidManifest.xml

Let’s try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project’s activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –

Click here to download the project code.

Источник

Получить размеры экрана java android

При разработке приложений под Android мы можем использовать различные типы измерений:

  • px : пиксели текущего экрана. Однако эта единица измерения не рекомендуется, так как реальное представление внешнего вида может изменяться в зависимости от устройства; каждое устройство имеет определенный набор пикселей на дюйм, поэтому количество пикселей на экране может также меняться
  • dp : (device-independent pixels) независимые от плотности экрана пиксели. Абстрактная единица измерения, основанная на физической плотности экрана с разрешением 160 dpi (точек на дюйм). В этом случае 1dp = 1px. Если размер экрана больше или меньше, чем 160dpi, количество пикселей, которые применяются для отрисовки 1dp соответственно увеличивается или уменьшается. Например, на экране с 240 dpi 1dp=1,5px, а на экране с 320dpi 1dp=2px. Общая формула для получения количества физических пикселей из dp: px = dp * (dpi / 160)
  • sp : (scale-independent pixels) независимые от масштабирования пиксели. Допускают настройку размеров, производимую пользователем. Рекомендуются для работы со шрифтами.
  • pt : 1/72 дюйма, базируются на физических размерах экрана
  • mm : миллиметры
  • in : дюймы

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

Разрешение экрана в Android

Используя же стандартные физические пиксели мы можем столкнуться с проблемой, что размеры элементов также будут сильно варьироваться в зависимости от плотности пикселей устройства. Например, возьмем 3 устройства с различными характеристиками экрана Nexus 4, Nexus 5X и Nexus 6P и выведем на экран квадрат размером 300px на 300px:

Физические пиксели в Android

В одном случае квадрат по ширине будет занимать 40%, в другом — треть ширины, в третьем — 20%.

Теперь также возьмем квадрат со сторонами 300х300, но теперь вместо физических пикселей используем единицы dp:

независимые от плотности пиксели в Android

Теперь же размеры квадрата на разных устройствах выглядят более консистентно.

Для упрощения работы с размерами все размеры разбиты на несколько групп:

  • ldpi (low) : ~120dpi
  • mdpi (medium) : ~160dpi
  • hdpi (high) : ~240dpi (к данной группе можно отнести такое древнее устройство как Nexus One)
  • xhdpi (extra-high) : ~320dpi (Nexus 4)
  • xxhdpi (extra-extra-high) : ~480dpi (Nexus 5/5X, Samsung Galaxy S5)
  • xxxhdpi (extra-extra-extra-high) : ~640dpi (Nexus 6/6P, Samsung Galaxy S6)

Установка размеров

Основная проблема, связанная с размерами, связана с их установкой в коде Java. Например, некоторые методы принимают в качестве значения физические пиксели, а не device-independent pixels. В этом случае может потребоваться перевести значения из одного типа единиц в другой. Для этого требуется применить метод TypedValue.applyDimension() , который принимает три параметра:

public static float applyDimension(int unit, float value, android.util.DisplayMetrics metrics)

Параметр unit представляет тип единиц, из которой надо получить значение в пикселях. Тип единиц описывается одной из констант TypedValue :

  • COMPLEX_UNIT_DIP — dp или независимые от плотности экрана пиксели
  • COMPLEX_UNIT_IN — in или дюймы
  • COMPLEX_UNIT_MM — mm или миллиметры
  • COMPLEX_UNIT_PT — pt или точки
  • COMPLEX_UNIT_PX — px или физические пиксели
  • COMPLEX_UNIT_SP — sp или независимые от масштабирования пиксели (scale-independent pixels)

Параметр value представляет значение, которое надо преобразовать

Параметр metrics представляет информацию о метрике, в рамках коорой надо выполнить преобразование.

В итоге метод возвращает преобразованное значение. Рассмотрим абстрактный пример. Например, нам надо получить из 60dp обычные физические пиксели:

int valueInDp = 60; int valueInPx = (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, valueInDp, getResources().getDisplayMetrics());

В качестве третьго аргумента передается вызов метода getResources().getDisplayMetrics() , который позволяет получить информацию о метрике, связанной с текущим устройством. В итоге мы получим из 60dp некоторое количество пикселей.

Источник

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