Android中擷取螢幕相關資訊(螢幕大小,狀態列、標題列高度)

來源:互聯網
上載者:User

下面介紹下在Android中如何擷取螢幕相關的資訊。

1.螢幕尺寸,原始碼如下:

DisplayMetrics metrics = new DisplayMetrics();getWindowManager().getDefaultDisplay().getMetrics(metrics);int screenWidth=metrics.widthPixels;            //螢幕寬度int screenHeight=metrics.heightPixels;        //螢幕高度

這段代碼可以插入到Activity的onCreate()函數中。

2、Java反射機制擷取系統@Hide屬性

如擷取狀態條高度

在源碼程式中代碼:

height= getResources().getDimensionPixelSize(com.android.internal.R.dimen.status_bar_height);

通過SDK擷取代碼:

class c = Class.forName("com.android.internal.R$dimen");Object obj = c.newInstance();Field field = c.getField("status_bar_height");int x = Integer.parseInt(field.get(obj).toString());int y = getResources().getDimensionPixelSize(x);


擷取標題列、狀態列高度:

Rect rect = new Rect();Window win = this.getWindow();win.getDecorView().getWindowVisibleDisplayFrame(rect);int statusBarHeight = rect.top;int contentViewTop = win.findViewById(Window.ID_ANDROID_CONTENT).getTop();int titleBarHeight = contentViewTop - Variable.statusBarHeight;   

//statusBarHeight為狀態列高度,titleBarHeight為標題列高度
      另外,這段代碼不能插入Activity的onCreate()和onResume()函數中,否則得到的兩個值都為0 。我的做法是將之插入到onPause()函數中,成功得到兩個正確值。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.