Get screen width and height in Android

前端 未结 30 3638
野的像风
野的像风 2020-11-22 09:28

How can I get the screen width and height and use this value in:

@Override protected void onMeasure(int widthSpecId, int heightSpecId) {
    Log.e(TAG, \"onM         


        
相关标签:
30条回答
  • 2020-11-22 10:16

    Full way to do it, that returns the true resolution:

                WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
                Point size = new Point();
                wm.getDefaultDisplay().getRealSize(size);
                final int width = size.x, height = size.y;
    

    And since this can change on different orientation, here's a solution (in Kotlin), to get it right no matter the orientation:

    /**
     * returns the natural orientation of the device: Configuration.ORIENTATION_LANDSCAPE or Configuration.ORIENTATION_PORTRAIT .<br></br>
     * The result should be consistent no matter the orientation of the device
     */
    @JvmStatic
    fun getScreenNaturalOrientation(context: Context): Int {
        //based on : http://stackoverflow.com/a/9888357/878126
        val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        val config = context.resources.configuration
        val rotation = windowManager.defaultDisplay.rotation
        return if ((rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_180) && config.orientation == Configuration.ORIENTATION_LANDSCAPE || (rotation == Surface.ROTATION_90 || rotation == Surface.ROTATION_270) && config.orientation == Configuration.ORIENTATION_PORTRAIT)
            Configuration.ORIENTATION_LANDSCAPE
        else
            Configuration.ORIENTATION_PORTRAIT
    }
    
    /**
     * returns the natural screen size (in pixels). The result should be consistent no matter the orientation of the device
     */
    @JvmStatic
    fun getScreenNaturalSize(context: Context): Point {
        val screenNaturalOrientation = getScreenNaturalOrientation(context)
        val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        val point = Point()
        wm.defaultDisplay.getRealSize(point)
        val currentOrientation = context.resources.configuration.orientation
        if (currentOrientation == screenNaturalOrientation)
            return point
        else return Point(point.y, point.x)
    }
    
    0 讨论(0)
  • 2020-11-22 10:16

    Two steps. First, extend Activity class

    class Example extends Activity
    

    Second: Use this code

     DisplayMetrics displayMetrics = new DisplayMetrics();
     WindowManager windowmanager = (WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
     windowmanager.getDefaultDisplay().getMetrics(displayMetrics);
     int deviceWidth = displayMetrics.widthPixels;
     int deviceHeight = displayMetrics.heightPixels;
    
    0 讨论(0)
  • 2020-11-22 10:16
           @Override
            protected void onPostExecute(Drawable result) {
                Log.d("width",""+result.getIntrinsicWidth());
                urlDrawable.setBounds(0, 0, 0+result.getIntrinsicWidth(), 600);
    
                // change the reference of the current drawable to the result
                // from the HTTP call
                urlDrawable.drawable = result;
    
                // redraw the image by invalidating the container
                URLImageParser.this.container.invalidate();
    
                // For ICS
                URLImageParser.this.container.setHeight((400+URLImageParser.this.container.getHeight()
                        + result.getIntrinsicHeight()));
    
                // Pre ICS`enter code here`
                URLImageParser.this.container.setEllipsize(null);
            }
    
    0 讨论(0)
  • 2020-11-22 10:21

    Using this code, you can get the runtime display's width & height:

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

    In a view you need to do something like this:

    ((Activity) getContext()).getWindowManager()
                             .getDefaultDisplay()
                             .getMetrics(displayMetrics);
    

    In some scenarios, where devices have a navigation bar, you have to check at runtime:

    public boolean showNavigationBar(Resources resources)
    {
        int id = resources.getIdentifier("config_showNavigationBar", "bool", "android");
        return id > 0 && resources.getBoolean(id);
    }
    

    If the device has a navigation bar, then count its height:

    private int getNavigationBarHeight() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            DisplayMetrics metrics = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(metrics);
            int usableHeight = metrics.heightPixels;
            getWindowManager().getDefaultDisplay().getRealMetrics(metrics);
            int realHeight = metrics.heightPixels;
            if (realHeight > usableHeight)
                return realHeight - usableHeight;
            else
                return 0;
        }
        return 0;
    }
    

    So the final height of the device is:

    int height = displayMetrics.heightPixels + getNavigationBarHeight();
    
    0 讨论(0)
  • 2020-11-22 10:21
    DisplayMetrics dimension = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(dimension);
            int width = dimension.widthPixels;
            int height = dimension.heightPixels;
    
    0 讨论(0)
  • 2020-11-22 10:21

    Kotlin Version via Extension Property

    If you want to know the size of the screen in pixels as well as dp, using these extension properties really helps:


    DimensionUtils.kt

    import android.content.res.Resources
    import android.graphics.Rect
    import android.graphics.RectF
    import android.util.DisplayMetrics
    import kotlin.math.roundToInt
    
    /**
     * @author aminography
     */
    
    private val displayMetrics: DisplayMetrics by lazy { Resources.getSystem().displayMetrics }
    
    val screenRectPx: Rect
        get() = displayMetrics.run { Rect(0, 0, widthPixels, heightPixels) }
    
    val screenRectDp: RectF
        get() = displayMetrics.run { RectF(0f, 0f, widthPixels.px2dp, heightPixels.px2dp) }
    
    val Number.px2dp: Float
        get() = this.toFloat() / displayMetrics.density
    
    val Number.dp2px: Int
        get() = (this.toFloat() * displayMetrics.density).roundToInt()
    
    

    Usage:

    class MainActivity : AppCompatActivity() {
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
    
            val widthPx = screenRectPx.width()
            val heightPx = screenRectPx.height()
            println("[PX] screen width: $widthPx , height: $heightPx")
    
            val widthDp = screenRectDp.width()
            val heightDp = screenRectDp.height()
            println("[DP] screen width: $widthDp , height: $heightDp")
        }
    }
    

    Result:

    When the device is in portrait orientation:

    [PX] screen width: 1440 , height: 2392
    [DP] screen width: 360.0 , height: 598.0
    

    When the device is in landscape orientation:

    [PX] screen width: 2392 , height: 1440
    [DP] screen width: 598.0 , height: 360.0
    
    0 讨论(0)
提交回复
热议问题