Determining the Size of an Android View or Screen at Run Time
For efficient bitmap handling or dynamic View creation in an App the area that a widget or layout is using needs to be known. If no fixed sizes are allocated at design time the size of a View may not be known until an App is executed. This is because of the wide range of display sizes that Android supports. The example code snippets in this articles shows how to read the screen size and the size of Views as the App runs. To run the example code you will need to create a new Android project (those new to Android programming can view the article Your First Android Hello World Java Program to see how), we called our App View Size.
In the layout designer for activity_main.xml (or whatever you called your layout) add another TextView, called textXY, next to the existing Hello world! widget. Change the Text on the first TextView to X,Y. Add this code to the oncreate method in MainActivity.java (or whatever class you are using), you will need an imports for TextView and DisplayMetrics. :
|
1 2 3 4 5 6 |
//object to store display information DisplayMetrics metrics = new DisplayMetrics(); //get display information getWindowManager().getDefaultDisplay().getMetrics(metrics); //show display width and height ((TextView)findViewById(R.id.textXY)).setText(Integer.toString(metrics.widthPixels)+","+Integer.toString(metrics.heightPixels)); |
This is the code running on an AVD with a 320×480 screen:

He is the layout used for this screen: Continue reading






