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. :
//object to store display information
DisplayMetrics metrics = new DisplayMetrics();
//get display information
//show display width and height
This is the code running on an AVD with a 320×480 screen:
He is the layout used for this screen: Continue reading
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 Button, Checkbox, EditText (a text box), ImageView, RadioButton, ProgressBar, TextView (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 RelativeLayout, LinearLayout, ScrollView, WebView 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
For 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
Simple Flip View Tutorial Using ViewPager for the Android Screen Swipe Effect
This introductory tutorial shows how to code a simple page swiping App with the ViewPager class. It is the basis for more complex view flipping examples, such as an image swiping gallery (to replace the Android Gallery widget that was deprecated in API 16). The ViewPager controls the swiping (flicking the screen left and right) between multiple screens or pages of data. The ViewPager is fed with the multiple screens by a PageAdapter (or the sub-classes FragmentPageAdapter and FragmentStatePagerAdapter).
The implementation of the PageAdapter will create (and destroy) the pages to be shown in the ViewPager. It will load the pages with the data (such as text or images) that must be displayed on the individual pages. This tutorial’s PageAdapter allows swiping through a series of strings (text). Once this example is complete it is easily extended. The follow on tutorial turns this example into a swiping image gallery with each image showing a caption. The following steps are performed to complete the screen swiping demo:
- Start a new Android App in Eclipse.
- Add the ViewPager widget to the Apps screen.
- Define the data (text) to be displayed on each swiped page.
- Define the layout for the swiped pages.
- Implement PageAdapter which will create each page and load it with data.
- Test the App.
Start a New Android App
This tutorial assumes that you are using Eclipse to try out this example code. Start by generating a new App in Eclipse, we called it Swipe Demo. (If you are new to Android programming see the articles Set Up Windows for Android Development and Your First Android Hello World Java Program.) You can of course add the page swiping effect to an existing App.
Adding the ViewPager Widget to the App’s Layout
The ViewPager is part of the Support Library, which is added by default to a new App created with a recent version of the Android API (the Support Library used to be known as the compatibility package). The ViewPager is referenced using it’s package name of android.support.v4.view.ViewPager. Open the default activity layout (or open the layout you are using) and add the ViewPager using the XML editing window, give it the id of viewPager. The ViewPager sits under the TextView (if using the layout created by the default Blank Activity after creating a new Android Application Project).
The TextView is also centered and the text changed from Hello world! to Please Swipe. It is made larger by assigning ?android:attr/textAppearanceMedium to the textAppearance attribute.
Defining the Data to Show on Each ViewPager Page
In this example some text is shown on each swiped page. Here the strings are stored in an array. The array could be defined in code but here they are in a resource file. Open the strings.xml file and add a string array. We are using the code names for Android version releases, all named after desserts: Continue reading
Understand How Layouts Center Views
Setting 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:
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.
When 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 Display A Smaller Window on Top of an Activity
The Activity screen is not the only way to interact with the user of an App. A brief message or dialog can be displayed in appropriate circumstances to ask a specific question or get specific input. Android has build in support for such small focused interactions that require immediate attention.
- The Toast class – to display brief informational only message.
- The Dialog class, managed by a DialogFragment – to support a flexible input that can display information and can ask for inputs or choices. There are several built in sub-classes including:
- AlertDialog – supports buttons (from zero to three), list selections, check boxes and radio buttons.
- ProgressDialog – supports a progress bar or wheel and supports buttons because it extends AlertDialog.
- DatePickerDialog – supports selecting a date.
- TimePickerDialog – supports a time selection.
- The PopupWindow class – allows a View to float on top of an existing activity. Suitable for custom informational messages.
These classes build their user interfaces through class methods with support from custom layouts when required. This article looks at using the PopupWindow class. What is the PopupWindow? The Android developer documention has the following class overview:
“A popup window that can be used to display an arbitrary view. The popup window is a floating container that appears on top of the current activity.”
It can be used to display extra information without needing to code another Activity. An example would be to show results at the end of a game (or end of a level), which we will be doing in the following tutorial. The steps for this example code are:
- Create a new project.
- Design the pop-up window.
- Add the code to load and populate the pop-up window.
- Call the code.
Open a Project to Add the Pop-Up Window
In this tutorial we are assuming that you have a working project in Eclipse to use as a base, either open an existing project or create a new one (if you need help see Your First Android Hello World Java Program).
Design the Layout for the Pop-Up
For this example we are going to have a pop-up to display a game’s result as gold, silver and bronze medal positions. The pop-up will have a graphic (ImageView) for each of the medals, a TextView for the winner’s name and one for the score. The images for the medals came from Open Clip Art Library user momoko. They have been resized for an Android project and you can download medals_png.zip ready for importing into a project.
A SimpleAdapter Loads a ListActivity with Two Line Entries
In the article Add a Simple List to an App example code was given to show how to load a ListActivity from a string array. This article shows how each list item in a ListActivity can display two lines of data, in this case each list item will be an American state and its capital. It is assumed that you know Java and that your computer is set up for Android development using Eclipse, if not see Set Up Windows for Android Development.
Start by creating a new Android Project in Eclipse using the File menu, select New then Android Project. Fill in the Project Name, here State Capitals is used. Click Next and select the build target from the installed APIs, e.g. Android 1.5, any of the installed APIs will work and it can be changed later if required. Click Next and enter the Package Name in the required format, e.g. biz.tekeye.statecapitals, leave Create Activity checked with the default Activity name, click Finish.
A common pattern in Android is to define a View in XML, set up the data that will be displayed in the View, then provide the code to load that data into the View. In the case of a ListView or ListActivity that code is provided by an Adapter. For a list with single line entries an ArrayAdapter does the job as seen in the previously mentioned article. Adding another line of data for each entry in the list requires the SimpleAdapter.
The code shown here will define a two dimensional string array to hold the American States names and capitals data. Two TextViews in a layout define the template for each list entry. The work of inflating the Views for each list entry and setting the values in the Views is done by a SimpleAdapter. An ArrayList and HashMap ensures the data goes into the correct TextView. This diagram summarises what the code achieves.