Tuesday, March 13, 2012

All About Views

In this tutorial, you will learn about different views in Android development, and how to reference them in code.
What is a View?

A View is a visual object in Android, such as a layout, a form control, or an image that can be displayed on the screen.

Here are a list of some common views and what they do:

  • TextView - A simple text box
  • EditText - A field for entering text. there are different varieties for passwords and numbers
  • Button - A clickable button
  • LinearLayout - A basic layout that arranges views either vertically or horizontally
  • RelativeLayout - A layout where objects are positioned in relation to each other, this layout is typically better to use than LinearLayouts for more complex layout
How to Reference A View:

The below code shows finding various views by IDs and saving them to variables:

TextView textBox = (TextView) findViewById(R.id.textBox); 
EditText textInput = (EditText) findViewById(R.id.textInput); 
LinearLayout container = (LinearLayout) findViewById(R.id.textInput);


Or more generally:

[[Type]] [variableName] = ([Type]) findViewById(R.id.[id]);


Where:
- Type = the name of the type of view being referenced (Such as TextView or EditText). The first place where Type is found can be omitted if the variable is previously declared.
- variableName = the name of the variable where the View will be stored
- id = the ID of the view being referenced. The ID and the variableName should match.

Explanation:

- findViewById(id) returns a View object for the specified id.
- (Type) The type cast converts the View to the desired subclass of View.
- Finally, the object is saved in the variable of the same type.

No comments:

Post a Comment