Professional Documents
Culture Documents
development - Tutorial
Lars Vogel (c) 2009, 2016 vogella GmbHVersion 14.4,20.06.2016
Table of Contents
1. High-level overview of Android development
o 1.1. The Android operating system
o 1.2. Android versions
o 1.3. Android application
o 1.4. Defining the user interface
o 1.5. Context
o 1.6. Android Developer Tools and Android Studio
o 1.7. System requirements
o 1.8. Download and installation of Android Studio
o 1.9. Managing the Android API level to develop against
o 1.10. Debug certificate and expire date
2. Exercise: Getting started with Android Studio
o 2.1. Create a new Android project
o 2.2. Review the generated project
o 2.3. Create a virtual device (AVD)
o 2.4. Start your virtual device
o 2.5. Start the application on your virtual device
3. Using Android devices for testing
o 3.1. Using a real Android device for testing
o 3.2. Using the Android emulator and Android Virtual Device
4. The Android manifest
o 4.1. Configuration of your Android application
o 4.2. Android manifest example
o 4.3. Version and package
o 4.4. Application and components
o 4.5. Minimum and target SDK
o 4.6. Permissions
o 4.7. Required device configuration
o 4.8. Installation location
o 4.9. More info
5. Resources
o 5.1. Resource files
o 5.2. Example: Defining strings, string arrays, colors and dimensions
o 5.3. Resource files and R.java
o 5.4. Layout files
o 5.5. Performance considerations with layouts
o 5.6. Good practices for resources IDs
o 5.7. System resources
o 5.8. References to resources in code
o 5.9. Accessing views from the layout in an activity
o 5.10. Reference to resources in XML files
o 5.11. Using assets?
6. Using views and view groups to design the user interface
o 6.1. View - The widgets in Android
o 6.2. Using a layout manager
o 6.3. Layout attributes
o 6.4. Overview of Android layout managers
o 6.5. ScrollView
7. Exercise: Your first view interaction
o 7.1. Review generated layout
o 7.2. Adjust views
o 7.3. Validate layout
o 7.4. Implement button behavior in your activity
o 7.5. Validate button interaction
o 7.6. Display text from your EditText field
o 7.7. Validate popup message
8. Exercise: Influence view layout at runtime
o 8.1. Add radio group and radio buttons to your layout
o 8.2. Change radio group orientation dynamically
o 8.3. Validating
9. Exercise: Using adapter views with a spinnner
o 9.1. Define a new resources file
o 9.2. Validating
10. Exercise: Using resources in XML files and in code
o 10.1. Add images to your application
o 10.2. Add widgets to display images to your layout
o 10.3. Replace images via button click
o 10.4. Validating
11. Exercise: Using ScrollView
12. Exercise: Create a temperature converter
o 12.1. Create Project
o 12.2. Create attributes
o 12.3. Creating the layout
o 12.4. Edit view properties
o 12.5. Create utiliy class
o 12.6. Change the activity code
o 12.7. Start the application
13. Deployment
o 13.1. How to deploy
o 13.2. Defining software and hardware requirements for the application
o 13.3. Signing your application for the release
o 13.4. Export your application via Android Studio
o 13.5. Export your application via the Eclipse IDE
o 13.6. Via external sources
o 13.7. Google Play
14. About this website
15. Android online resources
o 15.1. Android core resources
o 15.2. Android learning resources
o 15.3. Android tools
Marshmallow 6.0 23
Lollipop 5.1 22
Lollipop 5.0 21
Honeycomb 3.2.x 13
Froyo 2.2.x 8
Eclair 2.1 7
Donut 1.6 4
Cupcake 1.5 3
o
(no code name) 1.1 2 5.4.
vog
(no code name) 1.0 1 ella
Gm
bH training and consulting support
Appendix A: Copyright and License
This tutorial describes how to create Android applications. It is based on the latest and greatest Android and
Android Studio release.
The Android operating system can be divided into the four areas as depicted in the following graphic. An
Android application developer typically works with the two layers on top to create new Android applications.
Applications - Contains the applications, like the Browser, Camera, Gallery, Music and Phone
Application framework - An API which allows high-level interactions with the Android system
Libraries and runtime - The libraries for many common framework functions, like graphic rendering, data
storage, web browsing. Also contains the Android Runtime, as well as the core Java libraries for running
Android applications.
Linux kernel - Communication layer for the underlying hardware.
Component Description
Application An Android application can have one Application class which is instantiated before any o
It is the last component which is stopped during application shutdown.
Table 2. Android application components
Component Description
If not explicitly defined, Android creates a default application object for your application.
Activity An activity is the visual representation of an Android application. An Android application can
Activities use views and fragments to create their user interface and to interact with the user.
Service A service performs tasks without providing an user interface. They can communicate with oth
and send notifications to the user. For example, a broadcast receiver can notify the user via th
Android.
Broadcast receiver A receiver can be registered to listen to system messages and intents. A receiver gets notified
(short: receiver) the specified event occurs.
For example, you can register a receiver for the event that the Android system finished the bo
register for the event that the state of the phone changes, e.g., someone is calling.
Content provider A provider defines a structured interface to application data. A provider can be used for acces
(short: provider) application, but can also be used to share data with other applications.
Android contains an SQLite database which is frequently used in conjunction with a content
database would store the data, which would be accessed via the provider.
Views are user interface widgets, e.g., buttons or text fields. Views have attributes which can be used to
configure their appearance and behavior.
Fragments are components which run in the context of an activity. A fragment encapsulates application logic
and layout information. It is therefore easier to reuse them and to support devices of different size. For example,
a smaller screen shows only one fragment with the option to navigate to the next screen. On a larger screen it
shows two fragments.
1.5. Context
Instances of the class android.content.Context provide the connection to the Android system and actual
device. It gives access to the system and application resources and services. For example, you can check the size
of the current device display via it.
Activities and services extend the Context class. Therefore, they can be directly used to access the Context.
== Android Studio overview and installation
The Android development tooling converts these files into an Android application. The tooling allows to
compile, package, deploy and start application which are developed. The Android Software Development
Kit (Android SDK) and the Gradle tooling contains the necessary tools for this.
The Android SDK contains the Android debug bridge (adb). adb is a tool that allows you to connect to a virtual
or real Android device. This allows managing the device or debugging your application.
Most of Androids configuration files are based on XML. The Android tools provide specialized editors for
Android specific files. These editors typically allow you to switch between the XML representation of the file
and a structured user interface.
The Android SDK is 32-bit, therefore on a 64-bit Linux system you need to have the package ia32-
libs installed. For Ubuntu you can do this via the following command.
Please check your distribution documentation if you are using a different flavor of Linux.
The download comes in two flavors, SDK Tools only and Android Studio Packages. You want to download the
Android Studio Package for your operation system.
Installation for Windows is simple, just launch the .exe you downloaded. On Max OSX drag and drop Android
Studio into the Applications folder.
On Linux unpack the downloaded ZIP file into an appropriate location for your applications. To launch Android
Studio, navigate to the android-studio/bin/ directory in a terminal and execute studio.sh.
The first time you start a new Android Studio installation, you have the option to import your existing settings.
Select Tools Android SDK Manager or the SDK Manager icon in the toolbar of Android Studio to open the
Android SDK manager.
In the Android SDK manager select the version of desired Android version the tree and press
the Install button. The following screenshot shows the selection for the API 18 version of Android.
The SDK Platforms tab is used to install API versions, which the SDK Tools is used to install the development
tools.
This debug certificate has an expiration date of 365 days from its creation date. When the certificate expires, you
will get a build error that the certificate has been expired.
To fix this problem, delete the debug.keystore file. The default storage location is:
Property Value
Android Studio automatically downloads the required Android SDK, if that has not already been done.
Depending on your installation, the next dialog might not be displayed.
The Android view does not show the real file structure. It shows a logical view of the application.
On the next screen select the latest API level for your AVD. You may need to select the option for additional
images as highlighted in the following screenshot.
Afterwards press the Finish button. This will create the AVD configuration and display it under the list of
available virtual devices.
You can resize the emulator interactively via the corners of the emulator window.
You may also need to install the driver for your mobile phone. Linux and Mac OS usually work out of the box
while MS Windows typically requires the installation of a driver.
Of course, the minimum Android version of your Android application needs to fit to the Android version
If you have several devices connected to your computer, you can select which one should be used. If only one
device is connected, the application is automatically deployed on this device.
3.2. Using the Android emulator and Android Virtual
Device
3.2.1. What are Android Virtual Device?
The Android tooling contains an Android device emulator. This emulator can be used to run an Android Virtual
Device(AVD).
These AVDs allow you to test your applications on selected Android devices without access to the real
hardware. Virtual devices give you the possibility to test your application for selected Android versions and a
specific configurations. Even if you have a physical Android device available, you should get familiar with the
creation and usage of AVDs.
During the creation of your AVD you define the configuration for the virtual device. This includes, for example,
the resolution, the Android API version and the density of your display.
You can define multiple AVDs with different configurations and start them in parallel.
If you stop and AVD during startup process the AVD might get corrupted. The first start may take long,
an older machine. On a modern machine it typically takes less than a minute for a new AVD to start.
After the AVD has started, you can control the GUI with the mouse. The emulator also provides access to the
phone buttons via a menu on the right side of the emulator.
Once started, dont stop the AVD during your development. If you change your application and want to test a
new version, you simply re-deploy your application on the AVD.
AVDs created for the Google API allow you to test applications which use Google Play services, e.g., the new
Google maps API or the new location services.
The dialog implies that you can select both options, but if you do, you get an error message that these op
together.
If you select the Snapshot option, the second time you start the device it is started very fast, because the AVD
stores its state if you close it. If you select Use Host GPU the AVD uses the graphics card of your host computer
directly which makes the rendering on the emulated device much faster.
An Android virtual device which uses the Intel system image is much faster in execution on Intel / AMD
hardware compared to the ARM based system image. This is because the emulator does not need to translate the
ARM CPU instructions to the Intel / AMD CPU on your computer.
After the download you find the driver in your Android installation directory in the extras/intel folder.
This additional installation step is required on Window to accelerate the Intel emulator. Only downloadin
Android does not make a difference.
After the installation, you can create a new AVD based on the Intel emulator. The emulator does start faster and
is way faster during the execution of your Android application.
Activities, services and content provider components of the application must be statically declared in this file.
Broadcast receiver can also defined here, or registered dynamically at runtime. The manifest is read by the
Android system during installation of the application. The Android system evaluates it and determines the
capabilities of the application.
The Gradle build system can add or modify the manifest file at build time. For example, the application version
is typically supplied by the Gradle build file.
<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="19" />
<application
android:name="RssApplication"
android:allowBackup="false"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="RssfeedActivity"
android:label="@string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</manifest>
Google Play requires that every Android application uses its own unique package name. Therefore it is a good
habit to use your reverse domain name here. This will avoid collisions with other Android applications.
versionCode must be an integer. The Android Market determines whether it should perform an update of the
applications for the existing installation based on that versionCode. You typically start with "1" and increase
this value by one if you roll-out a new version of your application.
The intent filter part in the Android manifest file, tells the Android runtime that this activity should be registered
as a possible entry point into the application and made available in the launcher of the Android system.
The <@string/app_name> value refers to resource files which contain the actual value of the application
name. The usage of a resource file makes it easy to provide different resources (e.g., strings, colors, icons) for
different devices and makes it easy to translate applications.
Similar to the <activity> tag, you can use the service, receiver and provider to declare other Android
components.
Value Description
minSdkVersion Define the minimum version of Android your application works on. This attribute is used as a filte
Play. A user cannot install your application on a device with a lower API level than specified in th
targetSdkVersion Specifies the version on which you tested and developed. If it is not equal to the API version of th
Android system might apply forward- or backward-compatibility changes. It is good practice to al
Android API version to take advantages of changes in the latest Android improvements.
4.6. Permissions
The Android manifest file must also contain the required permissions for the application. For example, if the
application requires network access, it must be specified here.
Your application can declare permissions with the <permission> tag and declare that it required a permission
with the <uses-permission> tag.
Certain permissions, like network access, are granted automatically on Android 6.0 or higher systems. Other
permissions must be confirmed by the users to become active.
<uses-configuration android:reqHardKeyboard="true"/>
The uses-feature section allows you to specify the required hardware configuration for your device. For
example, the following snippet would require that the device has a camera.
In reality this option is rarely used, as an application installed on the external storage is stopped once the device
is connected to a computer and mounted as USB storage.
5. Resources
5.1. Resource files
Static resources like images and XML configuration files are used in Android applications.
Resource files must be placed in the /res directory of your application in a predefined sub-folder. The specific
sub-folder depends on type of resource which is stored. You can also append additional qualifiers to the folder
name. These are called resource qualifiers. These qualifiers indicate that the related resources should be used for
special device configurations. For example, you can specify that a layout file is only valid for a certain screen
size.
The following table gives an overview of the supported resources and their standard folder prefixes.
Table 5. Resources
Drawables /res/drawables Images (e.g., png or jpeg files)or vector drawables or XML files which scale autom
the Android device
Simple /res/values Used to define strings, colors, dimensions, styles and static arrays of strings or inte
Values convention each type is stored in a separate file, e.g., strings are defined in the res/
Layouts /res/layout XML files with layout descriptions are used to define the user interface for activiti
Styles and /res/values Files which define the appearance of your Android application.
themes
Animations /res/animator Defines animations in XML for the animation API which allows to animate arbitra
over time.
Raw data /res/raw Arbitrary files saved in their raw form. You access them via an InputStreamob
Table 5. Resources
Menus /res/menu Defines the actions which can be used in the toolbar of the application.
<string name="app_name">Test</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string-array name="operationsystems">
<item>Ubuntu</item>
<item>Android</item>
<item>Microsoft Windows</item>
</string-array>
<color name="red">#ffff0000</color>
<dimen name="mymargin">10dp</dimen>
</resources>
If you add a new resource file, the corresponding reference is automatically created in a R.java file. Manual
changes in the R.java file are not necessary and will be overwritten by the tooling. The Android system provides
methods to access the corresponding resource files via these IDs.
For example, to access a String with the R.string.yourString ID in your source code, you would use
thegetString(R.string.yourString) method defined on the Context class.
Defining layouts via XML layout files is the preferred way. This separates the programming logic from the
layout definition. It also allows the definition of different layouts for different devices.
A layout resource file is referred to as layout. A layout specifies the ViewGroups, Views, their relationship
and their attributes via an XML representation.
The following code is an example for a simple layout file.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="@+id/mytext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
</RelativeLayout>
A layout is assigned to an activity via the setContentView() method calls, as demonstrated in the following
example code.
package com.vogella.android.first;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
The Android SDK uses the camelCase notation for most of its IDs, e.g., buttonRefresh. It is good practice
to follow this approach.
The following shows an example in which a button gets the button1 ID assigned via
theandroid:id="@+id/button1" parameter. By conversion this statement creates a new ID if necessary
in the R.javafile and assigns the defined ID to the corresponding view.
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Preferences" >
</Button>
It is good practice to define IDs in one central configuration file. This is typically called ids.xml and placed in
the/res/values folder. This allows you to use the predefined ID in your layout file. If you want to define the id in
a separate file, you first need to remove the @+id entries in your layout files, otherwise you get an error
messages that these files have already been created. The following listing shows an example for such a file.
<Button
android:id="@id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_marginRight="27dp"
android:text="Button" />
</RelativeLayout>
While the above is good practice for real projects, the tutorials of this {textselfreference} avoid the usage
this setup is time consuming.
An instance of the Resources class is also required by other Android framework classes. For example, the
following code shows how to create a Bitmap file from a reference ID.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = (TextView) findViewById(R.id.mytext);
It is also possible to search in a view hierarchy with the findViewById(id) method, as demonstrated in the
following code snippet.
// note, you could have directly searched for R.id.mytext, the above coding
// is just for demonstration purposes
You could also build a utility method which makes access to views easier.
package com.example.android.test;
import android.app.Activity;
import android.view.View;
This would allow you to find the view without explicit cast in your view hierarchy.
For example, if you want to refer to a color, which is defined in an XML resource, you can refer to it
via @color/your_id. Or if you defined a String with the "titlepage" key in an XML resource, you
could access it via @string/titlepage
To use an Android system resource, include the android namespace into the references,
e.g., android.R.string.cancel.
You could also store unstructured data in the /res/raw folder. But it is considered good practice to use the
data.
You access this data via the AssetsManager which you can access via the getAssets() method from an
instance of the Context class.
The AssetsManager class allows you to read a file in the assets folder as InputStream with
the open() method. The following code shows an example for this.
All views in Android extend the android.view.View class, this class provides a lot of base functionality for
subclasses. For example, it provides the base support for touch.
The main packages for views are part of the android.view namespace for all the base classes
and android.widgetfor the default widgets of the Android platform.
Android supports different default layout managers. Layout managers can be nested to create complex layouts.
Children can specify their desired width and height via the following attributes.
Views can define their size. This can be done in units of measurement or via pre-defined layout values. For
example, as 100dp.
The match_parent value tells the application to maximize the widget in its parent.
The wrap_content value tells the layout to allocate the minimum amount so that the widget is rendered
correctly. The effect of these elements is demonstrated in the following graphics.
6.4.2. FrameLayout
FrameLayout is a layout manager which draws all child elements on top of each other. This allows to create
nice visual effects.
The following screenshot shows the Gmail application which uses FrameLayout to display several button on
top of another layout.
6.4.3. LinearLayout
LinearLayout puts all its child elements into a single column or row depending on
the android:orientationattribute. Possible values for this attribute
are horizontal and vertical. horizontal is the default value.
If horizontal is used, the child elements are layouted as indicated by the following picture.
6.4.4. RelativeLayout
RelativeLayout allows positioning the widget relative to each other. This can be used for complex layouts.
RelativeLayout is a complex layout manager and should only be used if such a complex layout is required, as it
performs a resource intensive calculation to layout its children.
A simple usage for RelativeLayout is if you want to center a single component. Just add one component to
the RelativeLayout and set the android:layout_centerInParent attribute to true.
<ProgressBar
android:id="@+id/progressBar1"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
/>
</RelativeLayout>
6.4.5. GridLayout
GridLayout allows you to organize views into a grid / table. GridLayout separates its drawing area into: rows,
columns, and cells.
You can specify how many columns the grid should have. For each view you can specify in which row and
column it should be placed and how many columns and rows it should use. If not specified, GridLayout uses
defaults, e.g., one column, one row and the view position depends on the order of the declaration.
<TextView
android:layout_column="0"
android:layout_columnSpan="3"
android:layout_gravity="center_horizontal"
android:layout_marginTop="40dp"
android:layout_row="0"
android:text="User Credentials"
android:textSize="32dip" />
<TextView
android:layout_column="0"
android:layout_gravity="right"
android:layout_row="1"
android:text="User Name: " >
</TextView>
<EditText
android:id="@+id/input1"
android:layout_column="1"
android:layout_columnSpan="2"
android:layout_row="1"
android:ems="10" />
<TextView
android:layout_column="0"
android:layout_gravity="right"
android:layout_row="2"
android:text="Password: " >
</TextView>
<EditText
android:id="@+id/input2"
android:layout_column="1"
android:layout_columnSpan="2"
android:layout_row="2"
android:inputType="textPassword"
android:ems="8" />
<Button
android:id="@+id/button1"
android:layout_column="2"
android:layout_row="3"
android:text="Login" />
</GridLayout>
The following code shows an example layout file which uses a ScrollView.
<TextView
android:id="@+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="8dip"
android:paddingRight="8dip"
android:paddingTop="8dip"
android:text="This is a header"
android:textAppearance="?android:attr/textAppearanceLarge" >
</TextView>
</ScrollView>
The android:fillViewport="true" attribute ensures that the scrollview is set to the full screen even if
the elements are smaller than one screen.
Investigate the XML layout in the visual editor as well in as the XML structure.
If necessary, change the layout manager to RelativeLayout. The result layout file should look similar to the
following file.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
</RelativeLayout>
Android Studio replaces placeholder values with the real values. This makes it sometimes harder to comp
the value in this case to see the placeholder value.
Add an Plain Text widget (EditText) and a Button to your layout. The easiest way is to find these elements in
the Paletteand drag and drop them into your layout.
Use the text (XML) editor to change the ID of the new EditText field to main_input. In the XML file this
looks like @+id/main_input.
Change the button text to Start via the android:text property in your layout file. Assign the
name onClick to the android:onClick property of your Button.
This defines that a public void onClick (View view) method is be called in the activity once
method is implemented in the next step.
After these changes your layout file should be similar to the following code.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<EditText
android:id="@+id/main_input"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/main_input"
android:layout_below="@+id/main_input"
android:layout_marginTop="31dp"
android:onClick="onClick"
android:text="Start" />
</RelativeLayout>
You see some warning messages in the editor, e.g., because you used hard-codes strings. These can be ig
applications.
If you run your application and press the button your application crashes because you still need to adjust your
activity.
You can get the right id via the R` class. It should be stored under ID and called main_input.
Use the text.getText().toString() method to read the string in the editor field and add the text to your
Toast message.
package com.vogella.android.first;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (BuildConfig.DEBUG) {
Log.d(Constants.LOG, "onCreated called");
}
setContentView(R.layout.activity_main);
}
// you may have here an onCreateOptionsMenu method
// this method is not required for this exercise
// therefore I deleted it
Table 6. ID Assignment
ID View
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/main_input"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start"
android:id="@+id/button"
android:layout_below="@id/main_input"
android:layout_alignParentStart="true"
android:onClick="onClick"/>
<RadioGroup
android:id="@+id/orientation"
android:layout_below="@id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp">
<RadioButton
android:id="@+id/horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Horizontal" >
</RadioButton>
<RadioButton
android:id="@+id/vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="Vertical" >
</RadioButton>
</RadioGroup>
</RelativeLayout>
Only the RadioGroup part needs to be added to your layout, the rest should already be there from prev
Implement a listener on the radio group which changes the orientation of the radio buttons. The new orientation
should be based on the current selection of the radio buttons. The selected button, is identified by the ID
parameter.
8.3. Validating
Run your application and select the different radio button. Ensure that the orientation of the radio buttons
changes based on your selection.
9.2. Validating
Start your application and validate the the spinner show the values from the array.
<!--
NOTE: More attributes are required
for the correct layout of the ImageView. These are left
out for brevity
-->
<ImageView
android:id="@+id/myicon"
.... more attributes
android:src="@drawable/ic_offline" />
10.4. Validating
Ensure that if you press your new button, the displayed image is replaced.
<LinearLayout
android:id="@+id/LinearLayout01"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="@+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="8dip"
android:paddingRight="8dip"
android:paddingTop="8dip"
android:text="This is a header"
android:textAppearance="?android:attr/textAppearanceLarge" >
</TextView>
<TextView
android:id="@+id/TextView02"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1.0"
android:text="@+id/TextView02" >
</TextView>
<LinearLayout
android:id="@+id/LinearLayout02"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<Button
android:id="@+id/Button01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1.0"
android:text="Submit" >
</Button>
<Button
android:id="@+id/Button02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1.0"
android:text="Cancel" >
</Button>
</LinearLayout>
</LinearLayout>
</ScrollView>
package de.vogella.android.scrollview;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
Start your application and ensure that you can scroll down to the buttons.
You can also scan the following barcode with your Android phone to install it via the Google Play application.
Property Value
Activity MainActivity
Layout activity_main
</resources>
Remove any existing view from your layout, either directly from the XML source or via the graphical editor.
Afterwards add an LinearLayout, another LinearLayout with one ViewText, EditText as children. Afterwards
add a RadioGroup with two radio buttons and a Button to your layout. Do this either directly in the XML file or
via the graphical editor. A simple way of organizing the components is to drag and drop them onto
the Component Tree view.
The result should look like the following screenshots. The first one shows the component view the second one
the preview.
Switch to the XML tab of your layout file and verify that the file looks similar to the following listing.
The Android tools team changes the generated code from time to time, so your XML might look slightly
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:background="@color/myColor">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/editText1" />
<RadioGroup
android:id="@+id/radioGroup1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="@+id/editText1"
android:layout_below="@+id/editText1">
<RadioButton
android:id="@+id/radio0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="RadioButton" />
<RadioButton
android:id="@+id/radio1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="RadioButton" />
</RadioGroup>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="@+id/radioGroup1"
android:layout_below="@+id/radioGroup1"
android:layout_marginTop="22dp"
android:text="Button" />
</LinearLayout>
You see some warning messages. You fix these in the following section of this exercise.
Ensure that the Checked property is set to true for the first RadioButton.
Assign @string/calc to the text property of your button and assign the value onClick to
the OnClick property.
Set the inputType property to numberSigned and numberDecimal on the EditText. As an example
you can use the last line in the following XML snippet. Also change its ID to "inputValue".
<EditText
android:id="@+id/inputValue"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_below="@+id/textView"
android:ems="10"
android:inputType="numberSigned|numberDecimal" />
All your user interface components are contained in a layout. Assign the background color to this Layout.
Select Color and then select myColor in the dialog. As an example, you can use the last line in the following
XML snippet.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:background="@color/myColor">
Afterwards the background should change to the whitesmoke color. It might be difficult to see the difference.
Switch to the activity_main.xml tab and verify that the XML is correct.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:background="@color/myColor">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/inputValue"
android:inputType="numberSigned|numberDecimal"/>
<RadioGroup
android:id="@+id/radioGroup1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="@+id/editText1"
android:layout_below="@+id/editText1">
<RadioButton
android:id="@+id/radio0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="@string/celsius" />
<RadioButton
android:id="@+id/radio1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/fahrenheit" />
</RadioGroup>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="@+id/radioGroup1"
android:layout_below="@+id/radioGroup1"
android:layout_marginTop="22dp"
android:text="@string/calc"
android:onClick="onClick"/>
</LinearLayout>
package com.vogella.android.temperatureconverter;
// converts to fahrenheit
public static float convertCelsiusToFahrenheit(float celsius) {
return ((celsius * 9) / 5) + 32;
}
}
package com.vogella.android.temperatureconverter;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (EditText) findViewById(R.id.inputValue);
}
// this method is called at button click because we assigned the name to the
// "OnClick" property of the button
public void onClick(View view) {
switch (view.getId()) {
case R.id.button1:
RadioButton celsiusButton = (RadioButton) findViewById(R.id.radio0);
RadioButton fahrenheitButton = (RadioButton) findViewById(R.id.radio1);
if (text.getText().length() == 0) {
Toast.makeText(this, "Please enter a valid number",
Toast.LENGTH_LONG).show();
return;
}
13. Deployment
13.1. How to deploy
In general there are restrictions how to deploy an Android application to your device. You can deploy the
application via USB in test mode onto your device, email yourself the application or use one of the many
Android markets to install the application. The following description highlights the most common ones.
Examples for such definitions are the presence of a certain hardware sensor or the availability of a camera.
For an overview of the available restrictions see http://developer.android.com/guide/topics/manifest/uses-
feature-element.html.
To install the Android application via another channel you need to sign the Android apk with a self-created
signature key.
Please note that you need to use the same signature key in Google Play (Google Market) to update your
application. If you lose the key, you will NOT be able to update your application ever again.
This requires a setting on the Android device which allows the installation of non-market application. Typically
this setting can be found under the "Security" settings.
Google Play also offers an update service. If a application developer uploads a new version of his application to
Google Play, this service notifies existing users about the available update.
Google Play provides access to services and libraries for Android application programmers, too. For example, it
provides a service to use and display Google Maps. Providing these services via Google Play has the advantage
that they are available for older Android releases. Google can update them without the need for an update of the
Android release on the phone.
Google Play requires a one time fee, currently 25 Dollar. After that payment, the developer can upload his
application and the required icons, via Google Play Publishing.
Google performs some automatic scanning of applications, but no approval process is in place. All application,
which do not contain malware, are published. Usually a few minutes after upload, the application is available.
Command line and GUI tools for produce Java source code from Android Dex and Apk files
The vogella company provides comprehensive training and education services from The vogella company of
experts in the areas of Eclipse RCP, Android, Git, Java, Gradle and Spring. We offer both consulting services, deve
public and inhouse training. Whichever course you decide to take, you are guaranteed to coaching. Our customers
experience what many before you refer to as The best IT class I have ever attended. corporations to individua
See Licence.
Version 14.4
Last updated 2017-03-01 07:36:12 +01:00