Android Programming

62
Android Programming Divya Pavani VIT UNIVERSITY 1

Transcript of Android Programming

Slide 1

Android ProgrammingDivyaPavaniVIT UNIVERSITY1 Android: IntroductionOne of the most widely used mobile OS these days isANDROID.Androidis a software bunch comprising not only operating system but also middleware and key applications.TheAndroidSDK provides the tools and APIs necessary to begin developing applications on the Android platform using the Java programming language.2Standalone ADT InstallationDownload Google provides a pre-packaged and configured Eclipse based Android development environment. The following link allows to download a archive file which includes all required tools for Android development.

http://developer.android.com/sdk/index.html3Extract the zip file and start Eclipse from theeclipsefolder via theeclipsenative launcher, e.g. eclipse.exeunder Windows.Install a specific Android version

4The dialog allows you to install and delete packages. SelectAvailable packagesand open theThird Party Add-ons. Select thelatest Google API(highest number) of the SDK and press theInstallbutton. Press theInstallbutton and confirm the license for all packages. After the installation completes, restart Eclipse.

5

Create & Run Android Virtual DeviceCreate AVD To define an Android Virtual Device (ADV) open theAVD Managerdialog viaWindowsAndroid Virtual Device Managerand press theNewbutton.

6Afterwards press theOKbutton. This will create the AVD configuration and display it under the list of available virtual devices.

7Run AVD To test if your setup is correct, select your new entry and press theStartbutton. After some time your AVD starts. Do not interrupt this startup process, as this might corrupt the AVD. After the AVD started, you can use the AVD via the mouse and via the virtual keyboard of the emulator.

8Create a Project with EclipseSelect "File/New/Project". In the "New Project" dialog, select "Android application Project" and click "Next".Fill in the form that appears:

9Application Nameis the app name that appears to users. For this project, use "My First App.Project Nameis the name of your project directory and the name visible in Eclipse.Package Nameis the package namespace for your appMinimum Required SDKis the lowest version of Android that your app supports, indicated using theAPI level.Target SDKindicates the highest version of Android (also using theAPI level) with which you have tested with your application.Compile Withis the platform version against which you will compile your app.Themespecifies the Android UI style to apply for your app.ClickNext.On the next screen to configure the project, leave the default selections and clickNext.The next screen can help you create a launcher icon for your app.ClickNext.Now you can select an activity template from which to begin building your app. For this project, selectBlankActivityand clickNext.Leave all the details for the activity in their default state and clickFinish.

10Running Your App Before you run your app, you should be aware of a few directories and files in the Android project:AndroidManifest.xml Themanifest file describes the fundamental characteristics of the app and defines each of its components.One of the most important elements your manifest should include is theelement. This declares your app's compatibility with different Android versions. Set theandroid:targetSdkVersionas high as possible and test your app on the corresponding platform version. For your first app, it should look like this:

11src/Directory for your app's main source files. By default, it includes anActivityclass that runs when your app is launched using the app icon.res/Contains several sub-directories forapp resources. Here are just a few:drawable-hdpi/Directory for drawable objects (such as bitmaps) that are designed for high-density (hdpi) screens. Other drawable directories contain assets designed for other screen densities.layout/Directory for files that define your app's user interface.values/Directory for other various XML files that contain a collection of resources, such as string and color definitions. When you build and run the default Android app, the defaultActivityclass starts and loads a layout file that says "Hello World.Run on the EmulatorRunfrom the toolbar.In theRun aswindow that appears, selectAndroid Applicationand clickOK.Eclipse installs the app on your AVD and starts it.

12

13

Building a Simple User InterfaceTwo common layout attributes android:layout_width, android:layout_height match_parent (fill up space in enclosing View) wrap_content (use natural size)

Lets build a simple interface which need to look like this:

14The given layout is currently designed with theEditTextandButtonwidgets.For the text field, because the user might type something longer. So, it would be nice to fill the unused screen width with the text field. You can do this inside aLinearLayout with theweightproperty, which you can specify using theandroid:layout_weight attribute.The default weight for all views is 0, so if you specify any weight value greater than 0 to only one view, then that view fills whatever space remains after all views are given the space they require. So, to fill the remaining space in your layout with theEditTextelement, give it a weight of 1 and leave the button with no weight.In order to improve the layout efficiency when you specify the weight, you should change the width of the EditTextto be zero (0dp). Setting the width to zero improves layout performance.15Heres a complete layout file should now look:

16Respond to the Send Button To respond to the button's on-click event, open theactivity_main.xmllayout file and add theandroid:onClickattribute to theelement:

Theandroid:onClickattributes value,"sendMessage", is the name of a method in your activity that the system calls when the user clicks the button.

17Open theMainActivityclass (located in the project'ssrc/directory) and add the corresponding method:

In order for the system to match this method to the method name given toandroid:onClick, the signature must be exactly as shown. Specifically, the method must:Be publicHave a void return valueHave aViewas the only parameter (this will be theViewthat was clicked)

18Build an IntentAnIntentis an object that provides runtime binding between separate components (such as two activities). TheIntentrepresents an apps "intent to do something." You can use intents for a wide variety of tasks, but most often theyre used to start another activity.In order for the next activity to query the extra data, you should define the key for your intent's extra using a public constant. So add theEXTRA_MESSAGEdefinition to the top of theMainActivityclass:

To start an activity, callstartActivity()and pass it yourIntent. The system receives this call and starts an instance of theActivityspecified by theIntent.

Create theDisplayMessageActivityclass in order for this to work.

19Create the Second Activity Create a new file namedDisplayMessageActivity.javain the project'ssrc/directory, next to the originalMainActivity.javafile.Update yourDisplayMessageActivityclass with the below code:

20Add the new activity's title to thestrings.xmlfile:

All activities must be declared in your manifest file,AndroidManifest.xml, using anelement.

21The completeonCreate()method forDisplayMessageActivitynow looks like this:

Run the app. When it opens, type a message in the text field, click Send, and the message appears on the second activity.

22

23Image Button

24

25Radio Button

CheckBox

26Toggle Button -- android:textOn, android:textOff The text for the two states. If you omit this, then the text is automatically ON and OFF (in caps)le Button.

27

28

29LayoutA layout defines the visual structure for a user interface, such as the UI for anactivity .Declare a layout in two ways:1.Declare UI elements in XML. Android provides a straightforward XML vocabulary that corresponds to the View classes and subclasses, such as those for widgets and layouts.2.Instantiate layout elements at runtime. Your application can create View and ViewGroup objects (and manipulate their properties) programmatically.

30Here we are going to declare a layout in XML:It enables you to better separate the presentation of your application from the code that controls its behavior. UI descriptions are external to your application code, which means that you can modify or adapt it without having to modify your source code and recompile. Able to create XML layouts for different screen orientations, different device screen sizes, and different languages. It is easier to debug problems. 31Some layouts are pre-defined by AndroidSome of these are LinearLayoutRelativeLayoutTableLayoutFrameLayoutAbsoluteLayoutA layout could be declared inside another layout32Linear Layout:Dispose views on a single row or column, depending on android:layout_orientationShows nested View elementsThe orientation could also be declared via setOrientation(int orientation)orientation is one of HORIZONTAL or VERTICALHas two other attributes:gravityweight

33

34Orientation=vertical

Orientation=horizontal35

36

37Relative Layout:Disposes views according to the container or according to other viewsThe gravity attribute indicates what views are more important to define the layoutUseful to align views

38

39

40Table Layout:As the name say, similar to a TableHas some attributes to customize the layout:android:layout_columnandroid:layout_spanandroid:stretchColumnsandroid:shrinkColumnsandroid:collapseColumnsEach row is inside a element41

4242Frame Layout:Display a single item at a time.Can have multiple elements within a Frame Layout.Elements that overlap will be displayed overlapping.Adds an attribute, android:visibilityMakes the user able to define layouts managing the visibility of views43

44Absolute Layout:Placing each control at an absolute position.Specify the exact x and y coordinates on the screen for each control. Deprecated-since absolutely positioning every element on the screen makes an inflexible UI that is much more difficult to maintain.Pay attention to different resolutions45