Obtain screen information (screen size, status bar, Title Bar Height) in Android)

Source: Internet
Author: User

The following describes how to obtain screen-related information in Android.

1. screen size, source code:

Displaymetrics metrics = new displaymetrics (); getwindowmanager (). getdefadisplay display (). getmetrics (metrics); int screenwidth = metrics. widthpixels; // screen width int screenheight = metrics. heightpixels; // screen height

This code can be inserted into the oncreate () function of the activity.

2. Get the system @ hide attribute using the Java reflection mechanism

For example, obtain the status bar height.

Code in the source code program:

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

Get code through 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);


Obtain the title bar and Status Bar Height:

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 indicates the height of the status bar and titlebarheight indicates the height of the title bar.
In addition, this Code cannot be inserted into the oncreate () and onresume () Functions of the activity. Otherwise, both values are 0. My practice is to insert it into the onpause () function and get two correct values successfully.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.