1. Trang chủ
  2. » Luận Văn - Báo Cáo

Báo cáo Thực hành Lập trình di động bằng Android Studio

133 73 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 133
Dung lượng 3,68 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Báo cáo tổng hợp thực hành lập trình di động cơ bản bằng Android Studio. Ngôn ngữ lập trình: Java, Kotlin.TABLE OF CONTENTCHAPTER I. INTRODUCTION TO ANDROID STUDIO61. Android Studio61.1. Download Android Studio for Window61.2. Install Android Studio72. Components in an Android project132.1. Activities132.2. Service142.3. Content Providers142.4. Broadcast Receivers152.5. Additional Components153. Folders and files in a project153.1. Manifests folder163.2. Java folder163.3. Resources folder173.4. Gradle scripts173.5. The Android Project View174. Create an Adroid project184.1. Configuration184.2. Run the application224.3. My First App25CHAPTER II. LAYOUT AND MEASUREMENTS281. Android Layouts281.1. What is layouts in an android application?281.2. Common layouts292. Measurements312.1. Dots per inch322.2. Density independence in Android323. Design a Simple Calculator33CHAPTER III. INTERACTIVE COMPONENTS AND EVENT HANDELING391. Basic Components392. Android UI Controls392.1. TextView392.2. EditText402.3. Button402.4. RadioButton402.5. Checkbox402.6. Spinner402.7. TimePicker402.8. DatePicker412.9. Toast413. Event Handling413.1. Event listeners413.2. Event handlers413.3. Event listeners registration424. Design a simple app to perform Event handling424.1. Design424.2. Event handling475. Design a simple app using Radio Button, Checkbox Toast485.1. Design485.2. Event Handling516. Program a Calculator Application52CHAPTER IV. DESIGN AND CUSTOMIZE UI561. Listview562. Custome listview563. Design a simple app using list view563.1. Design563.2. Event handling594. CTU form604.1. Design614.2. Event handling68CHAPTER V. DATABASE MANAGEMENT – SQLITE741. SQLite in Android742. Design a simple app using SQLite752.1. Design752.2. Event handling823. Reproduce application873.1. Design883.2. Event handling914. Program an electrical index recording application974.1. Design974.2. Event handling116CHAPTER VI. GOOGLE FIREBASE1301. Google Firebase1302. Group Project1302.1. Requirement1302.2. Design1302.3. Program130REFERENCES131

Trang 1

TABLE OF CONTENT

CHAPTER I INTRODUCTION TO ANDROID STUDIO 6

1 Android Studio 6

1.1 Download Android Studio for Window 6

1.2 Install Android Studio 7

2 Components in an Android project 13

2.1 Activities 13

2.2 Service 14

2.3 Content Providers 14

2.4 Broadcast Receivers 15

2.5 Additional Components 15

3 Folders and files in a project 15

3.1 Manifests folder 16

3.2 Java folder 16

3.3 Resources folder 17

3.4 Gradle scripts 17

3.5 The Android Project View 17

4 Create an Android project 18

4.1 Configuration 18

4.2 Run the application 22

4.3 My First App 25

CHAPTER II LAYOUT AND MEASUREMENTS 28

1 Android Layouts 28

1.1 What are layouts in an android application? 28

1.2 Common layouts 29

2 Measurements 31

2.1 Dots per inch 32

2.2 Density independence in Android 32

3 Design a Simple Calculator 33

CHAPTER III INTERACTIVE COMPONENTS AND EVENT HANDLING 39

1 Basic Components 39

2 Android UI Controls 39

2.1 TextView 39

Trang 2

2.3 Button 40

2.4 RadioButton 40

2.5 Checkbox 40

2.6 Spinner 40

2.7 TimePicker 40

2.8 DatePicker 41

2.9 Toast 41

3 Event Handling 41

3.1 Event listeners 41

3.2 Event handlers 41

3.3 Event listeners registration 42

4 Design a simple app to perform Event handling 42

4.1 Design 42

4.2 Event handling 47

5 Design a simple app using Radio Button, Checkbox & Toast 48

5.1 Design 48

5.2 Event Handling 51

6 Program a Calculator Application 52

CHAPTER IV DESIGN AND CUSTOMIZE UI 56

1 Listview 56

2 Custom listview 56

3 Design a simple app using list view 56

3.1 Design 56

3.2 Event handling 59

4 CTU form 60

4.1 Design 61

4.2 Event handling 68

CHAPTER V DATABASE MANAGEMENT – SQLITE 74

1 SQLite in Android 74

2 Design a simple app using SQLite 75

2.1 Design 75

2.2 Event handling 82

3 Reproduce application 87

3.1 Design 88

Trang 3

3.2 Event handling 91

4 Program an electrical index recording application 97

4.1 Design 97

4.2 Event handling 116

CHAPTER VI GOOGLE FIREBASE 130

1 Google Firebase 130

REFERENCES 132

Trang 4

TABLE OF TABLES

Table 1 Additional componets in Android 15

Table 2 Android Project View 18

Table 3 Density 32

Table 4 Event Listeners 41

Table 5 Envent Handlers 41

Table 6 SQLiteOpenHelper methods 74

Table 7 SQLiteDatabase methods 75

TABLE OF FIGURES Figure 1 Activities 14

Figure 2 Content providers 15

Figure 3 Android file structure 16

Figure 4 Select a project template 19

Figure 5 Configure project 20

Figure 6 Android Studio IDE 21

Figure 7 Work with xml file 21

Figure 8 Android Virtual Device Manager 22

Figure 9 Randomizer (Lab 1): Result 25

Figure 10 My First App (Lab 1): Result 26

Figure 11 Visualization of a view hierarchy with layout parameters associated with each view Source: https://developer.android.com/images/layoutparams.png 29

Figure 12 Frame Layout 30

Figure 13 Linear Layout 31

Figure 14 Table Layout 31

Figure 15 Density 32

Figure 16 Simple Calculator (Lab 2): UI Design 33

Figure 17 Event handler application (Lab 4): UI design 42

Figure 18 Event handler application (Lab 4): Component tree 43

Figure 19 Event hander application (Lab 4): Result 47

Figure 20 Course feedbacck (Lab 5): UI design 48

Figure 21 Course feedback (Lab 5): Component tree 49

Figure 22 Course feedback (Lab 5): Result 51

Figure 23 Simple Calculator (Lab 3): Result 53

Figure 24 Phonebook (Lab 6): Component tree for a row 57

Figure 25 Phonebook (Lab 6): UI design for a row 57

Figure 26 Phonebook (Lab 6): Result 59

Figure 27 CTU form (Lab 7 + 8): UI design for main activity 61

Figure 28 CTU form (Lab 7 + 8): Component tree for main activity 61

Figure 29 CTU form (Lab 7 + 8): Component tree for a row 65

Figure 30 CTU form (Lab 7 + 8): UI design for a row 66

Figure 31 CTU form (Lab 7 + 8): Result – Add new value 68

Figure 32 CTU form (Lab 7 + 8): Result - Store values to ListView 68

Trang 5

Figure 33 Note application (Lab 9): Component tree for main activity 76

Figure 34 Note application (Lab 9): UI design for main activity 76

Figure 35 Note application (Lab 9): Component tree for a row 77

Figure 36 Note application (Lab 9): UI desing for a row 78

Figure 37 Note application (Lab 9): Component tree for not detail activity 79

Figure 38 Note application (Lab 9): UI design for note detail activity 80

Figure 39 Note application (Lab 9): Result 82

Figure 40 Reproduce application (Lab 10): UI design for main activity 88

Figure 41 Reproduce application (Lab 10): Component tree for an item 89

Figure 42 Reproduce application (Lab 10): UI design for an item 90

Figure 43 Reproduce application (Lab 10): Result 91

Figure 45 Electrical index recording app (Lab 11): Component tree for main activity 97

Figure 44 Electrical index recording app (Lab 11): UI design for main activity 98

Figure 46 Electrical index recording app (Lab 11): Component tree for a customer row 99 Figure 47 Electrical index recording app (Lab 11): Component tree for add new customer activity 100

Figure 48 Electrical index recording app (Lab 11): UI design for add new customer activity 101

Figure 49 Electrical index recording app (Lab 11): Component for editting and deleting customer actitivy 104

Figure 50 Electrical index recording app (Lab 11): UI design for editting and deleting customer activity 104

Figure 51 Electrical index recording app (Lab 11): Components for add new record activity 106

Figure 52 Electrical index recording app (Lab 11): Component tree for adding a new record activity 107

Figure 53 Electrical index recording app (Lab 11): UI design for adding a new record activity 108

Figure 54 Electrical index recording app (Lab 11): Component tree for editting and deleting a record activity 111

Figure 55 Electrical index recording app (Lab 11): UI design for editting and deleting a record activity 112

Figure 56 Electrical index recording application (Lab 11): Customer management 116 Figure 57 Electrical index recording application (Lab 11): Bill (Record) management 116

Trang 6

CHAPTER I INTRODUCTION TO ANDROID STUDIO

1 ANDROID STUDIO

Android Studio is the official Google IDE for development of Android applications It was first announced in 2013 at the Google I/O conference and is able to be downloaded on Windows, macOS and Linux based operating systems

The advent of Android Studio contributes significantly to simplifying programming and developing mobile applications Specifically, building a mobile application involves a lot

of different stages The first step is to write the application code using a personal computer

or laptop The second step is to build the app to create the setup file After that, the installation file will be copied into the mobile device to install the application and run test (testing) It means that each time a line of code is changed, the program must be re-installed and re-run on the device which is incredibly time consuming and effortless Therefore, Android Studio, which is the official Google IDE for the development of Android applications, was created to solve these issues

Android Studio offers even more features that enhance your productivity when building Android apps, such as:

 A flexible Gradle-based build system

 A fast and feature-rich emulator

 A unified environment where you can develop for all Android devices

 Apply Changes to push code and resource changes to your running app without restarting your app

 Code templates and GitHub integration to help you build common app features and import sample code

 Extensive testing tools and frameworks

 Lint tools to catch performance, usability, version compatibility, and other problems

 C++ and NDK support

 Built-in support for Google Cloud Platform, making it easy to integrate Google Cloud Messaging and App Engine

1.1 Download Android Studio for Window

To download the latest version of Android Studio, access the website via the following link: https://developer.android.google.cn/studio

- Choose a suitable download options and click the download button or link

Trang 7

- Check the terms and conditions and begin to download Android Studio for Windows

1.2 Install Android Studio

- Step1: Launch the exe file that has just downloaded above and install the application

Trang 10

- Setup SDK

Trang 13

2 COMPONENTS IN AN ANDROID PROJECT

Application components are very essential for building Android applications They work

as an entry point for users or systems to enter your application There are four basic components and each one has its own purpose and distinct life cycle Additionally, there are also some additional application components

2.1 Activities

An activity is a class that is considered as an entry point for users that represents a single screen, in-short activity performs actions on the screen Most of the applications have more than one activity For example, a messenger application might have an activity that shows

a new notification, another activity which reads messages and another which composes a new message Among all those activities, one should be marked as the activity that is presented when the application is launched Generally, it is referred to MainActivity()

and the rest are its ChildActivities() This main activity interacts with the child activity and lets the user access them

Each activity is independent of one another For instance, a camera application can be started in an email application to compose an email that shares an image At each step, activities are stored in a stack, wherein the current activity holds the highest position (foreground activity) The picture below depicts how each new activity adds an item to back stack and how the current activity is destroyed and previous activity is resumed

Trang 14

Figure 1 Activities

An activity can have four states, which are running, paused, resumed and stopped In brief,

an activity is considered as running if it is shown in the foreground of the users’ screen

when the user is interacting with it Running state is also known as the top of the activity stack and the highest priority activity in Android The second-highest priority satisfies in

Android is paused state In this state, the activity is not in the focus but is still alive for the

user The activity comes in this state when some other activity comes in with the higher position in the window Then, when an activity goes from the paused state to the foreground

that is an active resumed state Finally, when an activity is no longer in the activity stack and not visible to the users anymore, it is in a stopped state

2.2 Service

A service is a general-purpose entry point for keeping an application running in the background for all kinds of reasons In other words, it is a component that runs in the background to conduct long-running operations or work for remote processes keeping updating data sources and activities Some examples of service are when users use other applications while it is playing music in the background or it can retrieve data over the network without preventing user interaction with an activity

2.3 Content Providers

A content provider is a component that allows applications to share data among multiple applications It manages the access to the central repository and supplies data between the applications on request In other words, the content provider allows users to gather the data centrally and provide them to applications It can be understood that it hides the database details but acts like a database, which can be added, deleted, inserted, updated the data

Trang 15

Figure 2 Content providers

2.4 Broadcast Receivers

A broadcast receiver is a component which allows the device to deliver events to the application outside of a regular user flow, responding to broadcast messages from another application or the same system Broadcast receivers can work even though the applications are not currently operating and have no user interfaces Broadcast can originate from the system or from applications Some examples of broadcast receivers are announcing when the battery of the device is low in the notification bar by the system or notifying other applications when data has been downloaded to the device and is available to use

1 Fragments Represents a portion of user interface in an activity

2 Views UI elements that art drawn on-screen including buttons, list forms,

etc

3 Layouts View hierarchies that control screen format and appearance of the

views

4 Intents Messages wiring components together

5 Resources External elements, such as strings, constants and drawable pictures

6 Manifest Configuration file for the application

3 FOLDERS AND FILES IN A PROJECT

The android project contains different type of app modules1, source code files and resource files Additionally, when launching a new Android project in Android Studio, it will immediately build a lot of files and directories and open the new project in the Android View, which is presented as:

Trang 16

of the project is shown in the Project View, along with all files covered from the Android View

Figure 3 Android file structure

3.1 Manifests folder

Manifests folder contains AndroidManifest.xml, which is one of the most important files

in the Android project structure It contains information about the application that the system must have before it can run any application code such as android version, metadata, states package for Kotlin file and other components It acts as an intermediator between Android OS and application [3] since configure properties for the application that the OS can understand and handle when it operates

3.2 Java folder

Java folder contains the Java and Kotlin source code and JUnit test files, which is created during developing the project and organized into packages An application can have more

Trang 17

than one package since its source code should be broken into different packages based on its core functionality

3.3 Resources folder

Resources folder is a very important folder since all graphics, layouts, strings and other resources that are associated with the project are stored in this directory Those external resources are divided into different subfolders, for example:

- Drawable folder contains the different type of images, bitmap files or XML files that are compiled into the drawable resource subtypes (bitmap files, state lists, shapes, animation, etc)

- Layout folder contains XML files that describe the views and layout or the UI for each activity of the application

- Mipmap folder is commonly and only used for the application icons, any other drawable assets should be placed in the drawable folder above

- Values folder stores XML files that describe various simple attribute values like strings, arrays, integers, dimensions, colors, styles, etc

3.4 Gradle scripts

Gradle scripts are used to automate tasks For the most part, Android Studio performs application builds in the background without any intervention from the developer This build process is handled using the Gradle system, an automated build toolkit designed to allow the ways in which projects are built to be configured and managed through a set of build configuration files It uses a language called groovy and contains a number of files which are used to define a build configuration which can be applied to all modules in our application In build.gradle (Project) there are build scripts and in build.gradle (Module) plugins and implementations are used to build configurations that can be applied to all our application modules [3] [4]

3.5 The Android Project View

When Project View is selected, there are a lot more files and directories are shown The most important of which are [2]:

Trang 18

Table 2 Android Project View

No File / Folder Description

1 module-name Contain the module files and directories

4 - src Contains all code and resource files for the module in

the subfolders

5 • androidTest Contains code for instrumentation test that run on an

Android device

6 • main Contains the “main” sourceset file: the Android code

and resources shared by all build variants

7 ▪ AndroidMainifest.xml Describes the nature of the application and each of tis

components

9 ▪ jni Contains native code using the Java Native Interface

10 ▪ gen Contains the Java files generated by Android Studio

11 ▪ res Contains application resources (drawable files, layout

files, UI string, etc)

12 ▪ assets Contains file that should be complied into an apk file

as-is

13 - test Contains code for local tests that run on host JVM

14 build.gradle (module) Defines the module-specific build configurations

15 build.gradle (project) Defines the build configuration apply to all modules

4 CREATE AN ANDROID PROJECT

In this section I will create an Android application called “Randomizers” [5] This app will randomly show a number in the customize range defined in a seek bar, whose maximum value is 10

In addition, the application was created according to the Android Developers guide [6] will

be presented in this section; however, I will not go into detailed instructions for this project 4.1 Configuration

To create a new Android project, first of all, in the Welcome to Android Studio window, click Create a new project or select File > New > New Project

Trang 19

In the Select a Project Template window, select Empty Activity for phone and click

Next.

Figure 4 Select a project template

In the Configure Your Project window, fill in some project information as below:

- Enter project name, in my case: Randomizer

- Enter "com.example.randomizer" in the Package name field

- Choose a folder to place the project in the Save location

- Select either Java or Kotlin from the Language drop-down menu I choose Kotlin

Trang 20

Figure 5 Configure project

It usually takes about 10 to 20 seconds for Android Studio to repair for the project There are some important files that needed to be reviewed as following: [6]

- app > java > com.example <project> > MainActivity : This is the main activity It's the entry point for your app When the application is built and run, the system launches an instance of this Activity and loads its layout

- app > res > layout > activity_main.xml : Defines the layout for the activity's user interface (UI) If this is a newly created project, it contains a

TextView element with the text “Hello, World!”

- app > manifest > AndroidManifest.xml : Describes the fundamental characteristics of the app and defines each of its components

- Gradle Scripts > build.gradle : There are two files with this name, one for the project and one for the app module As mention before, a project may have several modules and each module has its own build.gradle file

As can be seen in the picture below, the Android applications have two parts, which are layout and activity references to the activity_main.xml and MainActivity.kt (or java) file In the picture below, we are inside the activity Inside the onCreate function, there is a line that says setContentView(R.layout.activity_main) , presenting the layout gets connected to the activity or making activity_main.xml into the layout

Trang 21

Figure 6 Android Studio IDE

On the activity_main.xml screen, Android Studio provides some views on the top left

of the window and in the middle, there is a space where we can create a layout by dragging and dropping views and also delete views by selecting them and then hitting backspace

Figure 7 Work with xml file

In the MainActivity.kt file, use the below code to program the randomizers functions

package com.example.randomizer

import androidx.appcompat.app.AppCompatActivity

Trang 22

import android.widget.Button

import android.widget.SeekBar

import android.widget.TextView

import kotlin.random.Random as Random

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {

4.2 Run the application

To run the project, we can use a virtual device or an Android phone connected to the computer with a USB cord Now, I will create a new virtual device for this project as well

as for any upcoming ones

In Android Studio, choose Tools > AVD Manager, and choose Create Virtual Device

Figure 8 Android Virtual Device Manager

Select a hardware

Trang 23

Select system image

Create a AVD

Trang 24

Start a AVD

Select Run > Run app to see result of the application

Trang 25

Figure 9 Randomizer (Lab 1): Result

4.3 My First App

(Lab 1)

Trang 26

Figure 10 My First App (Lab 1): Result

Trang 27

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {

super.onCreate(savedInstanceState)

setContentView(R.layout.activity_main)

}

fun sendMessage(view: View) {

val editText = findViewById<EditText>(R.id.editText)

val message = editText.text.toString()

val intent = Intent(this, DisplayMessageActivity::class.java).apply {

putExtra(EXTRA_MESSAGE, message)

}

startActivity(intent)

}

Trang 28

class DisplayMessageActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {

super.onCreate(savedInstanceState)

setContentView(R.layout.activity_display_message)

val message = intent.getStringExtra(EXTRA_MESSAGE)

val textVarargs = findViewById<TextView>(R.id.textView).apply {

1.1 What are layouts in an android application?

Android Layout is used to define the user interface which holds the UI controls or widgets that will appear on the screen of an android application or activity

Generally, every application is a combination of View and ViewGroup As we know, an android application contains a large number of activities and we can say each activity is one page of the application So, each activity contains multiple user interface components and those components are the instances of the View and ViewGroup

Layout basically refers to the arrangement of elements on a page; these elements are likely

to be images, texts or styles These are a part of Android Jetpack They define the structure

of Android user interface which holds the UI controls or widgets like buttons, labels, textboxes and many others that will be shown on the screen of an application or activity All elements in the layout are built with the help of Views and ViewGroups2 [6] In fact,

an Android application has various activities and each activity also has a large number of

UI components, those components are the instances of the View and ViewGroup

Layout can be declared in two ways:

- Declare UI elements in XML Android includes a fundamental and clear XML

vocabulary that refers to the View classes and subclasses, such as those for widgets and layouts

- Instantiate layout elements at runtime The framework will programmatically

construct View and ViewGroup objects and also modify their properties

2 A ViewGroup is a special view that can contain other views

Trang 29

Figure 11 Visualization of a view hierarchy with layout parameters associated with each

view Source: https://developer.android.com/images/layoutparams.png

1.2 Common layouts

1.2.1 Constraint layout

ConstraintLayout is a ViewGroup subclass, used to specify the position of a layout constraints for every child View relative to other views present A ConstraintLayout is similar to a RelativeLayout , but it is more flexible and powerful It is now a default layout

in Android Studio since it provides many ways to place objects and constrain them to their container, to each other or to guidelines This allows developers to create large, complex, dynamic and responsive views in a flat hierarchy as well as using animation

1.2.2 Frame layout

Frame Layout is designed to block out an area on the screen to display a single item Generally, FrameLayout should be used to hold a single child view, because it can be difficult to organize child views in a way that's scalable to different screen sizes without the children overlapping each other [8] However, multiple objects can be added to a FrameLayout and their position can be controlled by assigning gravity to each, using the android:layout_gravity attribute Child views are drawn in a stack, with the most recently added child on top The size of the FrameLayout depends on the size of its largest child Since FrameLayout is the simplest ViewGroup and its computation time to layout the child views in it is the shortest, it can be said that it has best performance, but its biggest disadvantages that it is hard to design complicated UI

Trang 30

Figure 12 Frame Layout

1.2.3 Relative Layout

RelativeLayout is a view group that displays child views in relative positions, which arranges objects according to the position of others New views are placed relative to the already existing views The position of each view can be specified as relative to sibling elements (such as to the left-of or below another view) or in positions relative to the parent RelativeLayout area (such as aligned to the bottom, left or center) RelativeLayout is the most commonly used layout in GUI designing since it is quite simple and easy to design highly complex UI

1.2.4 Linear layout

LinearLayout is a ViewGroup that is responsible for holding views in it It is a layout that arranges its children linearly, in a single column (vertically) or a single row (horizontally) Relative Layout All children of a LinearLayout are stacked one after the other; therefore,

a vertical list will only have one child per row, no matter how wide they are, and a horizontal list will only be one row By default the orientation of this layout is horizontal, this direction can be modified by using android:orientation attribute LinearLayout has all advantages of the Relative Layout plus the possibility to develop UI for many different sized devices

Trang 31

Figure 13 Linear Layout

1.2.5 Table layout (Tabular Layout)

A TableLayout is a ViewGroup that arranges its children in a table form with rows and columns It can be considered as a group of TableRow objects, each of which defines a single row The number of columns depends on the number of objects in a table row, which means a column can be automatically added when there is any object added in the table row The table will have as many columns as the row with the most cells Each row can have zero or more cells and a cell can empty as well as span multiple columns TableLayout containers do not display border lines for their rows, columns, or cells

Figure 14 Table Layout

There are also other layouts and views such as AbsoluteLayout, GridLayout, GridView, ListView, WebView, etc

2 MEASUREMENTS

Android supports some measurements, which are listed in the table below:

Trang 32

px Pixels Actual pixels or dots on the screen

mm Millimeters Physical size of the screen in millimeters

dpi Dots per inch The pixel density which is the number of pixels

within a physical area of the screen

dp (aka dip)

Similar to dp unit, but also scaled by the user’s font size preference

2.1 Dots per inch

The pixel density is a calculation that returns the number of physical pixels per inch on a screen or display of a device It is often referred to as pixels per inch (PPI) This is different from the resolution, which is the total number of pixels on a screen as well as density- independent pixels (dip) Similarly, dots per inch (dpi) is a measure of spatial printing, video or image scanner dot density, in particular the number of individual dots that can be placed in a line within the span of 1 inch (2.54 cm) [9]

Figure 15 Density

2.2 Density independence in Android

An abstract unit that is based on the physical density of the screen The ratio of dp-to-pixel will change with the screen density, but not necessarily in direct proportion Convert dp units to pixel units: 𝑝𝑥 = 𝑑𝑝 ∗ (𝑑𝑝𝑖/160)

Table 3 Density

Density

density

mdpi Resources for medium-density screens, also the baseline

Trang 33

xhdpi Resources for extra-high-density screens ~320dpi xxhdpi Resources for extra-extra-high-density screens ~480dpi xxxhdpi Resources for extra-extra-extra-high-density uses ~640dpi

nodpi

Resources for all densities These are density-independent resources The system does not scale resources tagged with this qualifier, regardless of the current screen's density

tvdpi

Resources for screens somewhere between mdpi and hdpi;

approximately 213dpi This is not considered a "primary" density group It is mostly intended for televisions and most apps shouldn't need it—providing mdpi and hdpi resources is sufficient for most apps and the system will scale them as appropriate

3 DESIGN A SIMPLE CALCULATOR

(Lab 2)

My calculator has 2 parts: display section and buttons section The display section has two TextViews: tv_result and tv_expression I used a table layout to design the buttons section and placed it at the bottom of the screen It has 5 rows and 4 columns, each cell contains a single button as in the picture below

There are 10 number buttons of natural number from 0 to 9, a dot (.) button, a backspace button, 5 operator buttons (+, -, *, /, =) and 3 quick access buttons (AC – allclear, sqrt, percent)

Figure 16 Simple Calculator (Lab 2): UI Design

Trang 34

3.1.1 values/colors.xml

Configure the res/values/colors.xml file as following:

<?xml version="1.0" encoding="utf-8"?>

<resources>

<color name="black">#FF000000</color>

<color name="white">#FFFFFFFF</color>

<color name="gray_20">#333333</color>

<color name="gray_65">#a6a6a6</color>

<color name="dark_orange">#ff8c00</color>

</resources>

3.1.2 values/strings.xml

Configure the res/values/strings.xml file as following:

<resources>

<string name="app_name">Calculator</string>

<string name="zero">0</string>

<string name="one">1</string>

<string name="two">2</string>

<string name="three">3</string>

<string name="four">4</string>

<string name="five">5</string>

<string name="six">6</string>

<string name="seven">7</string>

<string name="eight">8</string>

<string name="nine">9</string>

<string name="dot">.</string>

<string name="all_clear">AC</string>

<string name="equal">=</string>

<string name="plus">+</string>

<string name="minus">-</string>

<string name="factor">&#0215;</string>

<string name="divide">&#0247;</string>

<string name="percent">%</string>

<string name="plus_minus">&#0177;</string>

<string name="backspace">⌫</string>

<string name="sqrt">&#8730;</string>

Trang 36

app:backgroundTint="@color/gray_65" /> <Button

android:layout_width="match_parent"

android:layout_height="70dp"

android:layout_marginLeft="4dp"

Trang 37

android:layout_weight="1"

android:text="@string/factor"

android:textSize="24sp"

app:backgroundTint="@color/dark_orange" /> </TableRow>

Trang 38

app:backgroundTint="@color/gray_20" /> <Button

android:layout_width="match_parent"

android:layout_height="70dp"

android:layout_marginLeft="4dp"

Trang 39

2.1 TextView

TextView is a UI component that displays the text to the user or display screen A TextView displays text to the user and optionally allows them to edit it A TextView is a complete text editor, however the basic class is configured to not allow editing There are various attributes to describe the TextView, some of them are named below:

- android:id – a unique id for the control

- android:fontFamily – font family (named by string) for text

- android:gravity – align the the text

- android:height – displays the exact height of the TextView

- android:hint – hint text to display when the text is empty

- android:password - whether the characters of the field are displayed as password dots instead of themselves Possible value either "true" or "false"

- android:text – text to display

- android:textColor – set the color of the text

- android:textColorHighlight – set the color of the text selection highlight

- android:width – displays the exact width of the TextView

Trang 40

2.2 EditText

A EditText is an overlay over TextView that configures itself to be editable or allows user

to enter some text It is the predefined subclass of TextView that includes rich editing capabilities Hence, EditText has many attributes that inherited from TextView and some more:

- android:id – a unique id for control

- android:autoText – if set, specifies that this TextView has a textual input method and automatically corrects some common spelling errors

- android:drawableBottom – this is the drawable to be drawn below the text

- android:drawableRight – this is the drawable to be drawn to the right of the text

- android:editable – if set, specifies that this TextView has an input method 2.3 Button

Button is a push-button that can be pressed, or clicked, by the user to perform an action There are various attributes to describe the Button, some of them are named below:

- android:id – a unique id for control

- android:background –a drawable to use as the background of the button

- android:onClick – name of the method in this View’s context to invoke when the button is clicked

- android:text – text to display

2.4 RadioButton

Radio button in Android is the one that has only two possible states, that are either checked

or unchecked Initially, it is in the unchecked state, once it’s checked it can’t be unchecked Normally, we use RadioGroup to define a group of Radio buttons that are alike, only one button can be chosen in the same group

2.5 Checkbox

A CheckBox is the UI control that has two states that are either checked or unchecked If

we have a group of CheckBox, user can select as many as we want, unlike RadioGroup 2.6 Spinner

The Spinner in Android is a User Interface that is used to select a particular option from a list of given options Spinner in Android is the same as dropdown in HTML It provides us with a faster way to select an option of our choice When we click on the down arrow, it shows a list of values from which we can select one By default, the first value would be shown as the currently selected Value [10]

Ngày đăng: 30/08/2021, 14:58

TỪ KHÓA LIÊN QUAN

🧩 Sản phẩm bạn có thể quan tâm

w