喵-见缝插针 2009-06-19 08:25 采纳率: 0%
浏览 550
已采纳

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

I created some custom elements, and I want to programmatically place them to the upper right corner (n pixels from the top edge and m pixels from the right edge). Therefore I need to get the screen width and screen height and then set position:

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

How do I get screenWidth and screenHeight in the main Activity?

转载于:https://stackoverflow.com/questions/1016896/get-screen-dimensions-in-pixels

  • 写回答

30条回答 默认 最新

  • 7*4 2009-06-19 08:41
    关注

    If you want the display dimensions in pixels you can use getSize:

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

    If you're not in an Activity you can get the default Display via WINDOW_SERVICE:

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

    If you are in a fragment and want to acomplish this just use Activity.WindowManager (in Xamarin.Android) or getActivity().getWindowManager() (in java).

    Before getSize was introduced (in API level 13), you could use the getWidth and getHeight methods that are now deprecated:

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

    For the use case you're describing however, a margin/padding in the layout seems more appropriate.

    Another way is: DisplayMetrics

    A structure describing general information about a display, such as its size, density, and font scaling. To access the DisplayMetrics members, initialize an object like this:

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

    We can use widthPixels to get information for:

    "The absolute width of the display in pixels."

    Example:

    Log.d("ApplicationTagName", "Display width in px is " + metrics.widthPixels);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(29条)

报告相同问题?

悬赏问题

  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元