How to Get View Size in Android

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. :

This is the code running on an AVD with a 320×480 screen:
Size of Android Screen

He is the layout used for this screen: Continue reading

Access Android View in Activity

In Android Get View Defined in XML in Activity Code

The UI screens for an App can be designed outside of the code. They are stored in XML files. This eases support for multiple screen sizes and types and helps with software maintenance. Classes in the Android SDK have methods used to access the UI components. Screens are composed of various implementations of the Android View class. The major sub-classes for Views are widgets and ViewGroups. The widget class is not to be confused with Widgets that can be added to the Android home screen. Instead View widgets are the normal components with which the Android device users interact, including the ButtonCheckboxEditText (a text box), ImageViewRadioButtonProgressBarTextView (label) and many more. Several widgets sit in a ViewGroup which provides a container for laying out components. Different ViewGroups provide different types of layouts, including RelativeLayoutLinearLayoutScrollViewWebView and others. ViewGroups can contain other ViewGroups as well as widgets therefore building complex displays by nesting different Views is possible.

Create a Basic Android Screen

A Simple Android ScreenFor this tutorial create a new, simple Android App project and call it Button Demo (if you don’t know how see Your First Android Hello World Java Program). A simple screen that just has a button on it was created using the starting layout, we kept the default layout name of activity_main.xml. In Eclipse use the Package Explorer to open the activity_main.xml file (in the res/layout folder). Using the Graphical Layout view (selected via the tabs at the bottom of the editor window) delete the TextView, showing Hello world!, and drag and drop a Button from the Form Widgets folder onto the screen. This screen’s code is stored in the activity_main.xml file:

To show how this view is accessed from the App’s code the text on the button will be changed and it displays a message when it is clicked. Continue reading

Center a TextView on a Android Screen

Understand How Layouts Center Views

Android RectanglesSetting the correct XML attributes to move a ViewGroup or widget (View) to the middle of the App’s display is easier if you know how Android screens are laid out. Everything on the screen is built up in rectangles, starting with the screen itself. A LinearLayout (which is a ViewGroup) sitting on the screen is a rectangle, a TextView in the LinearLayout is a rectangle. Each rectangle has two sets of layout attributes associated with it, attributes that refer to its contents and attributes that refer to its parents layout requirements. The latter is easy to determine because they all start with layout_. The number of layout_ attributes that a widget, such as a TextView, can access will vary depending upon the ViewGroup it is inside:

ViewGroup LayoutParams List

To help remember that the layout_ attributes refer to the items parent ViewGroup think of it as “attributes that lay outside” of the rectangle.

The two layout_ attributes that are always required are android:layout_width and android:layout_height. These are set to tell the parent ViewGroup how big the rectangle should be to contain the child widget or ViewGroup. These are usually set to either match_parent (previously known as fill_parent) which lets the ViewGroup decide how big the rectangle should be (usually as big as possible), or wrap_content which makes the rectangles just big enough to hold what is inside of them. However, they can also be set to physical dimensions, such as setting layout_height to 40px to make the View’s height 40 pixels high.

Centring Android TextWhen a new Android project is started in Eclipse with a blank Activity some default Hello world! text is displayed in a TextView. What if we wanted to center this in the middle of the screen (note we use the American spelling instead of the UK spelling of centre to match the Android SDK API settings). Looking at the various layout attributes for the TextView it would appear that android:layout_gravity=”center” would work. This though has no effect because the default RelativeLayout arranges child Views based on each others position. Instead to center the TextView set android:gravity=”center” for the RelativeLayout. Because this attribute does not start with layout_ it refers to it contents, in this case the TextView. This time centering works, provided the TextView’s  android:layout_width and android:layout_height are set to wrap_content, making it small enough to be moved to the central location.

See also the Layouts article in the developer documentation.

How to Set a Color In Android

Changing Colors in Android and Naming Them for Convenience

An Android color is a 32-bit integer value consisting of four eight bit parts, ARGB. The four parts are the amount of red, green and blue that is in the color, plus how opaque (see through) is the color, which is called the alpha value, the lower the alpha value the more transparent the color appears. (Note that in the United Kingdom color is spelt colour.)

The alpha value is the highest (first) byte in the 32-bit value followed by the red, then green and finally the blue byte. Hence it is referred to as an ARGB value with each letter representing the type and order of the byte. This format allows for easy representation as a hexadecimal number in Java:

The three byes representing the color values provide over 16 million color possibilities in Android (256 x 256 x 256 = 16,777,216). A color depth better than the human eye (stated in the Wikipedia article). Plus all these colors can range from transparent, 0, to opaque, 255.

Named Color Resources in Android

To help with handling colors in Android they can be made into a resource for easy of reuse. Either open an existing resource file or create a new one. For example in Eclipse with a Android project open select the res/values folder. Then use the File menu (or the context menu on the values folder) to add an Android XML File. Give the file a name, e.g. colors.xml and add a color element:

Use getColor() to read the color value from the resource.

If the color is solid (full alpha value) then the color resource can leave the alpha value out. Though for clarity and future maintenance it is wise to be explicit and always define all four parts of an Android color: Continue reading

Starting Emulator Failed to Allocate Memory

What to Try When The Android Emulator Reports A Memory Allocation Error

Occasionally when starting an Android Virtual Device (AVD) or running a project that starts an AVD in Eclipse an allocate memory error is reported. In the Starting Android Emulator dialog a message is seen similar to this one:

Starting emulator for AVD ‘Name of AVD’
Failed to allocate memory: 8
This application has requested the Runtime to terminate it in an unusual way.
Please contact the application’s support team for more information.

For example:

Android Failed To Allocate Memory

This article examines the reason for this error and possible solutions.

Why AVDs Need Large Amount of Memory

The latest Android devices now come with large memories, 1 GiB is now normal, and even larger memories will come in the future. When developing Apps for such devices it is natural to test them on AVDs that have the same specifications as the real world devices. When an AVD is set up using the AVD Manager program it is possible to choose existing device definitions. The Nexus 7 definition sets the RAM to 1024 MiB (1GiB). The RAM setting for the AVD is not all the RAM that the AVD uses. More RAM is required by the system to host and run the emulator code. An AVD given 1024 MiB can use up to 1.5 GiB when it is running. It makes having a high specification machine important when developing Android Apps.

Why AVD Memory Allocation Fails

The Failed to allocate memory:8 error usually occurs because the AVD is configured to have a large amount of RAM (>768 MiB) and the host Operating System (OS) appears not to be in a position to allocate that amount to the AVD (remember it needs to allocate more than specified because of the overhead in running the AVD). The OS may have plenty of memory available but it seems it is not currently in a position to allocate such a large chunk. For example the following screen shot shows the memory status on a Windows 7 64 bit machine with 8GB of memory that displayed the above error when an AVD to emulate a Nexus 7 attempted to start:

Windows resmon Example

This screenshot from the Windows Resource Monitor utility (perfmon.exe /res) shows virtually no free memory, but that is OK because there is plenty of Standby memory, 5.7 GiB. Standby is the memory cache and is available to newly starting programs (Windows will free cached memory when other programs need it). So why did the AVD fail to get a memory allocation? Continue reading

What are DPI, DIP, DP, PPI, SP and Screen Resolutions in Android?

Understanding Android Screen Densities and Terminology

Portrait v LandscapeThis article provides an overview of Android screen densities and the various acronyms that occur when dealing with a device’s screen. Android’s popularity as a mobile device Operating System has resulted in a proliferation of hardware on the market. This has provided great choice for the consumer and forced continuous innovation from the manufacturers. In a few short years there has been rapid innovation in all areas: CPU capabilities, memory size, form factors, keypads, cameras, sensors, batteries, power consumption and screen technologies. The screens have been getting bigger, thinner, sharper, tougher and more responsive to touch. This has forced the Android SDK to move rapidly with the hardware technology (and the hardware to feed upon Android ideas). Explained here is how the variety of screen sizes are handled by the OS, finishing with a summary table of the acronyms covered.

What makes up an Android Screen

Android Coordinate SystemFor those of you new to technology here’s how a device screen works. The screen is made of thousands of small dots called pixels arranged in a grid. The pixels running from left to right are known as the X pixels or X-axis. The pixels running from top to bottom are known as Y pixels or Y-axis. The resolution of the display is the number of pixels in X-axis multipled by the number of pixels in the Y-axis. A 320 by 480 display will have 320 pixels in the X-axis and 480 pixels in the Y-axis, this will also be stated simply as 320×480 (and in this case x is the multiplication, or times, sign and not the X-axis!).

To show an image on the display the color of the pixels are set by a program running on the device. Look at the article How Computer Screens and Printers Show Images for more details on how dots make up an image. Because the Android coordinate system runs left to right and top to bottom then plotting a line from 0,0 to 100,100 results in a line that slopes down from the top left of the screen, compared to one that slopes up from bottom left on a normal maths chart.

To get a idea of the variety of screens seen on Android devices look at the article Example List of Android Device Screen Resolutions and Sizes (which also shows that the various screen resolutions are given names). Continue reading

AdMob Ad Incorporated into an Android Activity

A Tutorial on Adding an AdMob Ad to an Android App

Displaying advertisements (ads) is one way of monetizing an App. To monetize (monetise) something is turn turn it into cash. That term applied to Apps and web pages refers to getting revenue through ads or paid content. Showing ads is one way of generating an income from the time and effort spent developing the App. Though a reasonably successful App is required to generate worthwhile funds. Other techniques include charging a price for the App and providing additional content within the App for a fee (In-App Billing).

Google makes it relatively easy to include ads into an App as the simple example code here shows. This tutorial should help those who may have found it difficult to get the example provided with the online AdMob documentation to work. It is assumed that your computer is configured for developing Apps using the Eclipse Integrated Development Environment (IDE) (see Set Up Windows for Android Development if not), and that you can create and run a simple App (see Your First Android Java Program if in doubt). All the steps required to get ad serving in your App working are covered. So read on to find out how to add AdMob to Android Apps.

Get an AdMob Account

You get a very small payment for each ad that is selected (clicked or pressed on) from a device that is running your App. So that Google can make that small payment it must identify in which App the ad was selected. This is done by placing a unique Publisher Id in the code that is showing the ads. To get the unique id for each App you need an AdMob account. Head over to http://www.google.com/ads/admob/ and sign up, you will need a Google account to register.

Target SDK Must be 3.2 or Higher

Your App is ready for publishing, lets put in the ad serving code so that when you activate it on Google Play it can (potentially) make you some money. In this tutorial we will add the code to an existing example project, in this case the code that was written for the article Two Line Lists In Android. You can also follow this tutorial but use your own App to add the code. Continue reading

Windows Symbolic Links for Android Installations on the D: Drive

AVDs Failing to Start if Eclipse is Not on C:

At Eye our machines are built for performance, shaving seconds of the program – compile – test cycle saves hours over the month. Machines have a small solid state drive (SSD) for the Operating System (Win 7 x64) and a big hard disk drive (HDD) for programs and work data. So Win 7 is on a C: drive and everything else on a D: drive. All users’ special folders are relocated to D:. For Android development Eclipse is installed with the Android Development Tools (ADT) Plugin onto the D: drive.

A lot of the initial development of an App is done using an Android Virtual Device (AVD). The AVD is set up using the AVD Manager. Once set up an AVD allows an App to be launched onto it via the Eclipse Run or Debug options. Unfortunately on some configurations where the user folders are on the D: drive, an error is reported when an AVD tries to start (even if the AVD Manager successfully created the AVD). A Starting Android Emulator dialog appears with an error message similar to PANIC: Could not open: C:\Users\Name\.android/avd/AVDName.ini.

AVD "PANIC: Could not open:..."  error

When debugging or running Apps ADT is trying to load the emulator from C: when it, and the configuration files for it, are on D:. One solution is to use a NTFS symbolic link, a.k.a a symlink. Setting up a symlink can fix the above error.

Open a command prompt in the user directory on C: (if you relocated all your special Windows folders to D: then there may only be a hidden Appdata folder in the user folder on C:). Use the mklink program to make a hard link to the .android directory on D:. If user John Doe moved all his Users files from C:\Users to D:\Users then the command to make the directory junction would be:

mklink /J "C:\Users\John Doe\.android" "D:\John Doe\.android"

mklink command for symlink (junction)

Now when the ADT plugin is trying to reference .android on C: NTFS redirects the request to D: and the emulator starts correctly.

(The mklink command is not shipped with Windows XP, to create a Directory Junction on Windows XP us the Sysinternal Junction tool.)

Google Play Publishing Graphics Checklist

You like your Android Phone or Tablet, it gives you easy portable computing with access to thousands of programs that cover almost any subject. Almost. That App that you wanted doesn’t exist so you’ve invested some time and energy and made it yourself. Now you’d like to publish it so that others can use it, and maybe make a little money on the side. Unfortunately you’ll need to break out the creative talents again and come up with some promotional graphics, because your App will not be listed on Google Play (formerly Android Market) unless those graphics are available. The following table lists the graphic and media images you will need to produce to publish on Google Play.

Media Assets Required for Google Play App Publishing
Item Type Opt. Size Alpha Padding
2 to 8 Screenshots 24-bit PNG/JPG No 320×480 or 480×800 or 480×854 No No
Large App Icon 32-bit PNG No 512×512 (1024KB max.) Yes Allowed
Promo Image 24-bit PNG/JPG Yes 180×120 No No
Feature Image 24-bit PNG/JPG Yes 1024×500 (924×400 useable) No Yes
YouTube Video Link URL Yes N/A N/A N/A

Notes:

  • Provide every asset for a professional app listing, even those that are optional.
  • PNG is a Portable Networks Graphics file, file extension normally .png.
  • JPG file extension is normally .jpg or .jpeg and is a Joint Photographics Expert Group graphics format.
  • All graphics sizes are give as X pixels times Y pixels (i.e. 320×480 is 320 pixels wide by 480 pixels high).
  • Alpha determines whether or not the alpha channel is support for the given image being used.
  • Do not put a border around the edge of any graphics.
  • Use large fonts, bright contrasting colors and crisp designs that are not overly detailed. Particularly for the Feature Image which may be scaled down.

See the article High Resolution App Icon for Google Play Publishing for a tutorial on generating the 512×512 image.

See the article Grabbing an Android Device Screenshot for information on generating the screenshots required.

The Google web page Graphic Assets for your Application has further details.