以像素为单位获取屏幕尺寸

我创build了一些自定义元素,我想以编程方式将它们放在右上angular(从顶部边缘n像素,从右边缘m像素)。 因此,我需要获取屏幕宽度和屏幕高度,然后设置位置:

 int px = screenWidth - m; int py = screenHeight - n; 

我如何在主Activity中获取screenWidthscreenHeight

如果你想以像素为单位的显示尺寸,你可以使用getSize

 Display display = getWindowManager().getDefaultDisplay(); Point size = new Point(); display.getSize(size); int width = size.x; int height = size.y; 

如果您不在Activity ,则可以通过WINDOW_SERVICE获取默认Display

 WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); Display display = wm.getDefaultDisplay(); 

在引入getSize之前(在API级别13中),可以使用现在不推荐使用的getWidthgetHeight方法:

 Display display = getWindowManager().getDefaultDisplay(); int width = display.getWidth(); // deprecated int height = display.getHeight(); // deprecated 

对于你描述的用例来说,布局中的边距/填充看起来更合适。

2015年10月22日

另一种方法是: DisplayMetrics

描述关于显示的一般信息的结构,例如其大小,密度和字体缩放。 要访问DisplayMetrics成员,请像这样初始化一个对象:

 DisplayMetrics metrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metrics); 

我们可以使用widthPixels获取以下信息:

“以像素为单位的显示的绝对宽度”

例:

 Log.d("ApplicationTagName", "Display width in px is " + metrics.widthPixels); 

一种方法是:

 Display display = getWindowManager().getDefaultDisplay(); int width = display.getWidth(); int height = display.getHeight(); 

它被弃用,你应该尝试下面的代码。 前两行代码为您提供了DisplayMetrics对象。 此对象包含像heightPixels,widthPixels等字段。

 DisplayMetrics metrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metrics); int height = metrics.heightPixels; int width = metrics.widthPixels; 

它可能不会回答你的问题,但是如果你需要一个视图的维度,但是当它的布局还没有布置的时候,你的代码正在被执行的时候,知道(我正在自己找这个问题的时候) (例如在onCreate() )中,您可以使用View.getViewTreeObserver().addOnGlobalLayoutListener()来设置ViewTreeObserver.OnGlobalLayoutListenerView.getViewTreeObserver().addOnGlobalLayoutListener()需要视图维度的相关代码放在那里。 监听器的callback将在布局布局时调​​用。

(2012年答案,可能已过时)如果你想支持前蜂窝,你需要在API 13之前,向后兼容。

 int measuredWidth = 0; int measuredHeight = 0; WindowManager w = getWindowManager(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) { Point size = new Point(); w.getDefaultDisplay().getSize(size); measuredWidth = size.x; measuredHeight = size.y; } else { Display d = w.getDefaultDisplay(); measuredWidth = d.getWidth(); measuredHeight = d.getHeight(); } 

当然,不赞成使用的方法最终会从最新的SDK中拿出来,但是我们仍然依赖大部分拥有Android 2.1,2.2和2.3的用户,这就是我们所剩下的。

我已经尝试了所有可能的“解决scheme”失败,我注意到,Elliott Hughes的“Dalvik Explorer”应用程序总是在任何Android设备/操作系统版本上显示正确的尺寸。 我结束了他的开源项目,可以在这里find: https : //code.google.com/p/enh/

以下是所有相关的代码:

 WindowManager w = activity.getWindowManager(); Display d = w.getDefaultDisplay(); DisplayMetrics metrics = new DisplayMetrics(); d.getMetrics(metrics); // since SDK_INT = 1; widthPixels = metrics.widthPixels; heightPixels = metrics.heightPixels; try { // used when 17 > SDK_INT >= 14; includes window decorations (statusbar bar/menu bar) widthPixels = (Integer) Display.class.getMethod("getRawWidth").invoke(d); heightPixels = (Integer) Display.class.getMethod("getRawHeight").invoke(d); } catch (Exception ignored) { } try { // used when SDK_INT >= 17; includes window decorations (statusbar bar/menu bar) Point realSize = new Point(); Display.class.getMethod("getRealSize", Point.class).invoke(d, realSize); widthPixels = realSize.x; heightPixels = realSize.y; } catch (Exception ignored) { } 

编辑:稍微改进版本(避免在不支持的操作系统版本上引发exception):

 WindowManager w = activity.getWindowManager(); Display d = w.getDefaultDisplay(); DisplayMetrics metrics = new DisplayMetrics(); d.getMetrics(metrics); // since SDK_INT = 1; widthPixels = metrics.widthPixels; heightPixels = metrics.heightPixels; // includes window decorations (statusbar bar/menu bar) if (Build.VERSION.SDK_INT >= 14 && Build.VERSION.SDK_INT < 17) try { widthPixels = (Integer) Display.class.getMethod("getRawWidth").invoke(d); heightPixels = (Integer) Display.class.getMethod("getRawHeight").invoke(d); } catch (Exception ignored) { } // includes window decorations (statusbar bar/menu bar) if (Build.VERSION.SDK_INT >= 17) try { Point realSize = new Point(); Display.class.getMethod("getRealSize", Point.class).invoke(d, realSize); widthPixels = realSize.x; heightPixels = realSize.y; } catch (Exception ignored) { } 

最简单的方法:

  int screenHeight = getResources().getDisplayMetrics().heightPixels; int screenWidth = getResources().getDisplayMetrics().widthPixels; 

要访问Android设备状态栏的高度,我们更喜欢通过编程的方式来获取它:

示例代码

 int resId = getResources().getIdentifier("status_bar_height", "dimen", "android"); if (resId > 0) { result = getResources().getDimensionPixelSize(resId); } 

variablesresult给出像素中的高度。

为了快速访问

在这里输入图像说明

有关Title barNavigation barContent View高度的更多信息,请查看Android设备屏幕大小

首先得到视图(例如,通过findViewById() ),然后你可以在视图本身上使用getWidth()

我有两个函数,一个用于发送上下文,另一个用像素获取高度和宽度:

 public static int getWidth(Context mContext){ int width=0; WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE); Display display = wm.getDefaultDisplay(); if(Build.VERSION.SDK_INT>12){ Point size = new Point(); display.getSize(size); width = size.x; } else{ width = display.getWidth(); // Deprecated } return width; } 

 public static int getHeight(Context mContext){ int height=0; WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE); Display display = wm.getDefaultDisplay(); if(Build.VERSION.SDK_INT>12){ Point size = new Point(); display.getSize(size); height = size.y; } else{ height = display.getHeight(); // Deprecated } return height; } 

对于使用XML进行dynamic缩放,有一个名为“android:layout_weight”的属性

下面的例子,从synic在这个线程中的响应中修改 ,显示一个button占据屏幕的75%(weight = .25),文本视图占据屏幕的剩余25%(weight = .75)。

 <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight=".25" android:text="somebutton"> <TextView android:layout_width="fill_parent" android:layout_height="Wrap_content" android:layout_weight=".75"> </LinearLayout> 

这是我使用的代码:

 // `activity` is an instance of Activity class. Display display = activity.getWindowManager().getDefaultDisplay(); Point screen = new Point(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) { display.getSize(screen); } else { screen.x = display.getWidth(); screen.y = display.getHeight(); } 

看起来很干净,但是,照顾的贬低。

这不是一个更好的解决scheme吗? DisplayMetrics提供您需要的所有function,并可从API 1中使用。

 public void getScreenInfo(){ DisplayMetrics metrics = new DisplayMetrics(); getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics); heightPixels = metrics.heightPixels; widthPixels = metrics.widthPixels; density = metrics.density; densityDpi = metrics.densityDpi; } 

您还可以使用getRealMetrics获取实际的显示(包括屏幕装饰,例如状态栏或软件导航栏),但仅适用于17+。

我错过了什么吗?

只是增加弗朗切斯科的答案。 另一个较为贴切的观察者,如果你想查找窗口中的位置或者屏幕上的位置,就是ViewTreeObserver.OnPreDrawListener()

这也可以用来查找onCreate()时间内大部分未知的视图的其他属性,例如滚动的位置,缩放的位置。

查找屏幕的宽度和高度:

 width = getWindowManager().getDefaultDisplay().getWidth(); height = getWindowManager().getDefaultDisplay().getHeight(); 

使用这个,我们可以得到最新的和以上的SDK 13。

 // New width and height int version = android.os.Build.VERSION.SDK_INT; Log.i("", " name == "+ version); Display display = getWindowManager().getDefaultDisplay(); int width; if (version >= 13) { Point size = new Point(); display.getSize(size); width = size.x; Log.i("width", "if =>" +width); } else { width = display.getWidth(); Log.i("width", "else =>" +width); } 

在Activity中使用下面的代码。

 DisplayMetrics metrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metrics); int height = metrics.heightPixels; int wwidth = metrics.widthPixels; 
 DisplayMetrics dimension = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dimension); int w = dimension.widthPixels; int h = dimension.heightPixels; 

需要说明的是,如果您不在Activity ,而是在View (或者在您的范围中具有Viewtypes的variables),则不需要使用WINDOW_SERVICE 。 那么你至less可以用两种方法。

第一:

 DisplayMetrics dm = yourView.getContext().getResources().getDisplayMetrics(); 

第二:

 DisplayMetrics dm = new DisplayMetrics(); yourView.getDisplay().getMetrics(dm); 

我们在这里调用的所有这些方法都不被弃用。

我发现这个伎俩。

 Rect dim = new Rect(); getWindowVisibleDisplayFrame(dim); 
 public class AndroidScreenActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); DisplayMetrics dm = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dm); String str_ScreenSize = "The Android Screen is: " + dm.widthPixels + " x " + dm.heightPixels; TextView mScreenSize = (TextView) findViewById(R.id.strScreenSize); mScreenSize.setText(str_ScreenSize); } } 

这不是OP的答案,因为他希望实际像素的显示尺寸。 我想在“设备无关像素”的尺寸,并从这里把答案从这里https://stackoverflow.com/a/17880012/253938和这里https://stackoverflow.com/a/6656774/253938我来了有了这个:;

  DisplayMetrics displayMetrics = Resources.getSystem().getDisplayMetrics(); int dpHeight = (int)(displayMetrics.heightPixels / displayMetrics.density + 0.5); int dpWidth = (int)(displayMetrics.widthPixels / displayMetrics.density + 0.5); 

有一个使用DisplayMetrics(API 1)来避免try / catch混乱的非弃用方法:

  // initialize the DisplayMetrics object DisplayMetrics deviceDisplayMetrics = new DisplayMetrics(); // populate the DisplayMetrics object with the display characteristics getWindowManager().getDefaultDisplay().getMetrics(deviceDisplayMetrics); // get the width and height screenWidth = deviceDisplayMetrics.widthPixels; screenHeight = deviceDisplayMetrics.heightPixels; 

我会像这样包装getSize代码:

 @SuppressLint("NewApi") public static Point getScreenSize(Activity a) { Point size = new Point(); Display d = a.getWindowManager().getDefaultDisplay(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { d.getSize(size); } else { size.x = d.getWidth(); size.y = d.getHeight(); } return size; } 

首先加载XML文件,然后写下这个代码:

 setContentView(R.layout.main); Display display = getWindowManager().getDefaultDisplay(); final int width = (display.getWidth()); final int height = (display.getHeight()); 

根据您的屏幕分辨率显示宽度和高度。

按照下面的方法:

 public static int getWidthScreen(Context context) { return getDisplayMetrics(context).widthPixels; } public static int getHeightScreen(Context context) { return getDisplayMetrics(context).heightPixels; } private static DisplayMetrics getDisplayMetrics(Context context) { DisplayMetrics displayMetrics = new DisplayMetrics(); WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); wm.getDefaultDisplay().getMetrics(displayMetrics); return displayMetrics; } 

在某个活动的onCreate中,有时您需要知道布局的可用空间的精确尺寸。 经过一番思考,我制定了这样做的方式。

 public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); startActivityForResult(new Intent(this, Measure.class), 1); // Return without setting the layout, that will be done in onActivityResult. } @Override protected void onActivityResult (int requestCode, int resultCode, Intent data) { // Probably can never happen, but just in case. if (resultCode == RESULT_CANCELED) { finish(); return; } int width = data.getIntExtra("Width", -1); // Width is now set to the precise available width, and a layout can now be created. ... } } public final class Measure extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Create a LinearLayout with a MeasureFrameLayout in it. // Just putting a subclass of LinearLayout in works fine, but to future proof things, I do it this way. LinearLayout linearLayout = new LinearLayout(this); LinearLayout.LayoutParams matchParent = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT); MeasureFrameLayout measureFrameLayout = new MeasureFrameLayout(this); measureFrameLayout.setLayoutParams(matchParent); linearLayout.addView(measureFrameLayout); this.addContentView(linearLayout, matchParent); // measureFrameLayout will now request this second activity to finish, sending back the width. } class MeasureFrameLayout extends FrameLayout { boolean finished = false; public MeasureFrameLayout(Context context) { super(context); } @SuppressLint("DrawAllocation") @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); if (finished) { return; } finished = true; // Send the width back as the result. Intent data = new Intent().putExtra("Width", MeasureSpec.getSize(widthMeasureSpec)); Measure.this.setResult(Activity.RESULT_OK, data); // Tell this activity to finish, so the result is passed back. Measure.this.finish(); } } } 

如果由于某种原因,您不想将其他活动添加到Android清单,则可以这样做:

 public class MainActivity extends Activity { static Activity measuringActivity; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle extras = getIntent().getExtras(); if (extras == null) { extras = new Bundle(); } int width = extras.getInt("Width", -2); if (width == -2) { // First time in, just start another copy of this activity. extras.putInt("Width", -1); startActivityForResult(new Intent(this, MainActivity.class).putExtras(extras), 1); // Return without setting the layout, that will be done in onActivityResult. return; } if (width == -1) { // Second time in, here is where the measurement takes place. // Create a LinearLayout with a MeasureFrameLayout in it. // Just putting a subclass of LinearLayout in works fine, but to future proof things, I do it this way. LinearLayout linearLayout = new LinearLayout(measuringActivity = this); LinearLayout.LayoutParams matchParent = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); MeasureFrameLayout measureFrameLayout = new MeasureFrameLayout(this); measureFrameLayout.setLayoutParams(matchParent); linearLayout.addView(measureFrameLayout); this.addContentView(linearLayout, matchParent); // measureFrameLayout will now request this second activity to finish, sending back the width. } } @Override protected void onActivityResult (int requestCode, int resultCode, Intent data) { // Probably can never happen, but just in case. if (resultCode == RESULT_CANCELED) { finish(); return; } int width = data.getIntExtra("Width", -3); // Width is now set to the precise available width, and a layout can now be created. ... } class MeasureFrameLayout extends FrameLayout { boolean finished = false; public MeasureFrameLayout(Context context) { super(context); } @SuppressLint("DrawAllocation") @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); if (finished) { return; } finished = true; // Send the width back as the result. Intent data = new Intent().putExtra("Width", MeasureSpec.getSize(widthMeasureSpec)); MainActivity.measuringActivity.setResult(Activity.RESULT_OK, data); // Tell the (second) activity to finish. MainActivity.measuringActivity.finish(); } } 

如果您不想要WindowManagers,Points或Displays的开销,那么您可以获取XML中最顶端的View项的高度和宽度属性,只要其高度和宽度设置为match_parent即可。 (只要您的布局占据整个屏幕,这是真的。)

例如,如果你的XML以这样的开始:

 <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/entireLayout" android:layout_width="match_parent" android:layout_height="match_parent" > 

然后findViewById(R.id.entireLayout).getWidth()将返回屏幕的宽度, findViewById(R.id.entireLayout).getHeight()将返回屏幕的高度。

谁在search可用的屏幕尺寸没有状态栏操作栏 (也感谢Swapnil的答案):

 DisplayMetrics dm = getResources().getDisplayMetrics(); float screen_w = dm.widthPixels; float screen_h = dm.heightPixels; int resId = getResources().getIdentifier("status_bar_height", "dimen", "android"); if (resId > 0) { screen_h -= getResources().getDimensionPixelSize(resId); } TypedValue typedValue = new TypedValue(); if(getTheme().resolveAttribute(android.R.attr.actionBarSize, typedValue, true)){ screen_h -= getResources().getDimensionPixelSize(typedValue.resourceId); } 

我有一个LinearLayout作为根视图的启animation面活动,它的宽度和高度都有match_parent 。 这是该活动的onCreate()方法中的代码。 我在应用程序的所有其他活动中使用这些措施。

 int displayWidth = getRawDisplayWidthPreHoneycomb(); int rawDisplayHeight = getRawDisplayHeightPreHoneycomb(); int usableDisplayHeight = rawDisplayHeight - getStatusBarHeight(); pf.setScreenParameters(displayWidth, usableDisplayHeight); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { LinearLayout myView = (LinearLayout) findViewById(R.id.splash_view); myView.addOnLayoutChangeListener(new OnLayoutChangeListener() { @Override public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) { if (left == 0 && top == 0 && right == 0 && bottom == 0) { return; } int displayWidth = Math.min(right, bottom); int usableDisplayHeight = Math.max(right, bottom); pf.setScreenParameters(displayWidth, usableDisplayHeight); } }); } 

以下是您在上面调用的方法的实现:

 private int getRawDisplayWidthPreHoneycomb() { WindowManager windowManager = getWindowManager(); Display display = windowManager.getDefaultDisplay(); DisplayMetrics displayMetrics = new DisplayMetrics(); display.getMetrics(displayMetrics); int widthPixels = displayMetrics.widthPixels; int heightPixels = displayMetrics.heightPixels; return Math.min(widthPixels, heightPixels); } private int getRawDisplayHeightPreHoneycomb() { WindowManager w = getWindowManager(); Display d = w.getDefaultDisplay(); DisplayMetrics metrics = new DisplayMetrics(); d.getMetrics(metrics); int widthPixels = metrics.widthPixels; int heightPixels = metrics.heightPixels; return Math.max(widthPixels, heightPixels); } public int getStatusBarHeight() { int statusBarHeight = 0; int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android"); if (resourceId > 0) { statusBarHeight = getResources().getDimensionPixelSize(resourceId); } return statusBarHeight; } 

对于所有API版本和不同types的设备(手机和平板电脑),这会导致可用显示的高度和宽度,不包括任何types的酒吧(状态栏,导航栏)。

为了获得屏幕尺寸,使用显示matrix

 DisplayMetrics displayMetrics = new DisplayMetrics(); if (context != null) WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); Display defaultDisplay = windowManager.getDefaultDisplay(); defaultDisplay.getRealMetrics(displayMetrics); } 

以像素为单位获取高度和宽度

 int height=displayMetrics.widthPixels; int width=displayMetrics.heightPixels; 

简单的function与较低版本兼容。

 /** * @return screen size int[width, height] * * */ public int[] getScreenSize(){ Point size = new Point(); WindowManager w = getWindowManager(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2){ w.getDefaultDisplay().getSize(size); return new int[]{size.x, size.y}; }else{ Display d = w.getDefaultDisplay(); //noinspection deprecation return new int[]{d.getWidth(), d.getHeight()}; } } 

使用:

 int width = getScreenSize()[0]; int height = getScreenSize()[1];