GUI Components, Activity, Fonts and Colors
GUI Components, Activity, Fonts and Colors
Statement Purpose:
Activity Outcomes:
After completing this chapter students will be able to understand the following topics.
- Activity
- Life Cycle of an Activity
- Creating an Activity
- Intents
- Types of Intents
- GUI Components
- Fonts and Colors
Instructor Note:
Activity
Activity is the basic building block of any android application. Android applications contain one or more Activities. The introduction of activity has been given in the previous chapter
‗Ingredients of an android application‘. As we have seen earlier, android activity always has a user interface.
When user launches an application, a window will be displayed. The whole window provides the user interface to the user, this screen makes an activity. . The controls placed in the UI allow the user to do a certain action. The controls in an activity can be created in two different ways. They can be created either by java code or by adding XML code to define the UI. The latter method is always preferred.
Activity stack
An android application usually contains lots of activities. We can navigate over these activities. When a user starts an activity, android OS pushes that into a stack. If user starts another activity then first activity goes down and newly started activity is added to the top of the stack. When user pushes back button, then top activity is destroyed and the activity which is below the top activity is resumed.
ACTIVITY
For example, a user receives a message on android phone. Now consider the actions performed by the user. By tracking those actions, we can understand how activity stack works. The user views the list of messages in inbox is activity 1. The user opens a message for reading is Activity 2 If the user replies to that message that becomes activity 3. If the user presses back button, then he gets activity 2 again. When he gets activity 2 again, the activity 3 is destroyed. Together these groups of activities form a task.
Task is a collection of activities that users interact with when performing a certain job. The activities are arranged in a stack (the back stack), in the order in which each activity is opened.
A representation of how each new activity in a task adds an item to the back stack. When the user presses the Back button, the current activity is destroyed and the previous activity resumes.
Life Cycle of an Activity
An android activity has a lifecycle during performing a few things. Why is it required? Let’s understand it with an example.
For example, a user is playing game in his mobile. During that time, he receives a call from someone. When playing game, if the user receives a call the game is paused and the calling window appears on top of the game screen. When the call ends, the user can resume the game at the point where he left. Here game is an application. When that application is interfered by any other activity or application, the state of the game application is saved.
How the game state is saved and resumed? There must be some technique to save the game state. To handle such situations android provides activity lifecycle. The life cycle of an activity is handled by a set of functions and they are invoked when something happens to the activity.
Activity States
An activity life cycle starts from creating an activity. A created activity, in a running application can be in one of the following three states:
- Resumed – Activity is running or in active state, it is focused and the user can interact with
- Paused – Activity is not running or focused, it might be covered by another activity, or is transparent)
- Stopped – Activity is stopped or not
When an activity goes from one state to another, the different life cycle methods are invoked where we can fill in with our code.
Methods for Activity Life Cycle
When an activity transitions from one state to another, set of callback methods are invoked for each state. How a set of call back methods for each state of an activity is invoked in its life cycle is given in the below picture.
Following are the available callback methods
- onCreate()
- onStart()
- onPause()
- onResume()
- onStop()
- onRestart()
- onDestroy()
onCreate The onCreate() method is called when an activity is created for the first time. This method is invoked only once during the entire lifecycle of an activity. To create an activity, we must override the onCreate() method which is available in the class named Activity.
Since this method is called only once at the beginning of an activity it can be used for initialization. As the onCreate() method is called while creating an activity, the method for setting the activity layout setContentView() is always invoked inside of this method. onStart:
The onStart() method is called after the creation of an activity and just before the activity becomes visible to the user. This onStart() method can be called from two places – after onRestart() and OnCreate(). i.e., after creating an activity to start it for a first time, or to restart an activity. This onStart() method can also be used to reset any data of an activity. onResume: The onResume() method is called when our activity comes into the foreground, from the paused state. We already discussed an example that receiving a call while playing game in a phone. In that example, when the received call is ended the game is resumed.
During that time (when game is resumed), the game activity is on top of the activity stack, so that the activity is ready to interact with user. onResume() is a good place to update the screen with new results. onPause: The onPause() method is invoked, when a new activity comes on top of the existing activity. Typically anything that steals the user away from an activity will result in calling onPause() method. The onPause() method can have the code for releasing resources, saving the application data, stopping background threads etc. It is always guaranteed that whenever the activity is becoming invisible or partially invisible, onPause() will be called. But once onPause() is called, android reserves the right to kill our activity at any point. Hence we should not be relying on receiving any further events. onStop:
The onStop() method gets called when an activity finishes its work or stopped by the user. We can use this method to shut down when we need to create time intensive or CPU intensive operations.
OnRestart: The onRestart() method is similar to onCreate(), but onRestart() is called only after onStop(). Through this method in an application, we can understand that whether the application is starting a fresh or getting restarted. When an activity invokes onRestart(), the activity state is stored and variables are reinitialised. onDestroy: This method is invoked at the last stage of an activity life cycle. When an activity is killed, the onDestroy() method is invoked. For example consider that when the user presses back button on any activity, the foreground activity gets destroyed and control will be returned to the previous activity. Even though, we use always onPause() and onStop() to clean up resources, the onDestory() allows our application to have another chance to do that before it exits. But there is no guarantee that onDestroy() will be called. It will be called only when the system is low on resources or user press the back button or if we use finish () explicitly in our code. Process Lifecycle The Android system attempts to keep application process around for as long as possible, but eventually will need to remove old processes when memory runs low. As described in Activity Lifecycle, the decision about which process to remove is intimately tied to the state of the user’s interaction with it. In general, there are four states a process can be in based on the activities running in it, listed here in order of importance. The system will kill less important processes (the last ones) before it resorts to killing more important processes (the first ones).
- The foreground activity (the activity at the top of the screen that the user is currently
interacting with) is considered the most important. Its process will only be killed as a last resort, if it uses more memory than is available on the device. Generally at this point the device has reached a memory paging state, so this is required in order to keep the user interface responsive.
- A visible activity (an activity that is visible to the user but not in the foreground, such as one sitting behind a foreground dialog) is considered extremely important and will not be killed unless that is required to keep the foreground activity running.
- A background activity (an activity that is not visible to the user and has been paused) is no longer critical, so the system may safely kill its process to reclaim memory for other foreground or visible processes. If its process needs to be killed, when the user navigates back to the activity (making it visible on the screen again), its onCreate(Bundle) method will be called with the savedInstanceState it had previously supplied in onSaveInstanceState(Bundle) so that it can restart itself in the same state as the user last left
- An empty process is one hosting no activities or other application components (such as Service or BroadcastReceiver classes). These are killed very quickly by the system as memory becomes low. For this reason, any background operation you do outside of an activity must be executed in the context of an activity BroadcastReceiver or Service to ensure that the system knows it needs to keep your process
Sometimes an Activity may need to do a long-running operation that exists independently of the activity lifecycle itself. An example may be a camera application that allows you to upload a picture to a web site. The upload may take a long time, and the application should allow the user to leave the application will it is executing. To accomplish this, your Activity should start a Service in which the upload takes place. This allows the system to properly prioritize your process (considering it to be more important than other non-visible applications) for the duration of the upload, independent of whether the original activity is paused, stopped, or finished. 3. Creating an Activity Creating an activity class is as simple as creating a class in java. It simply involves creating a class and overriding a method. To create an activity, we need to extend the Activity class which is available in the android.app package. The onCreate() method must be overridden in order to create a new activity. The example code gives an understanding of creating an activity class and event handling in android. In an android project,
- Create an xml file under layout folder which is available in app/src/main/res
- Create an activity class under app/src/main/java folder
Layout XML file By default, an xml file named activity_main.xml is available under res/layout folder. We can create user interface through two ways either by xml file or by java code. But the previous technique is preferred i.e., through xml file. Using the palette available in
android studio, design the user interface. When controls are created, automatically code is placed in the xml file as shown below.
For each control an id is given which will be used as a reference to that control in code. Here the attribute android:id contains the id for the control EditText. The code for the controls is placed inside opening and closing layout tag. The layout tag looks like as follows.
activity_main.xml
<RelativeLayout xmlns:android xmlns:tools=”http:// schemas.android.com/tools” android:layout_width=”match_parent” android:layout_height=”match_parent” android:paddingLeft=”@dimen/activity_horizontal_margin” android:paddingRight=”@dimen/activity_horizontal_margin” android:paddingTop=”@dimen/activity_vertical_margin” android:paddingBottom=”@dimen/activity_vertical_margin” tools:context=”.MainActivity”>
<EditText android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/ editText” android:layout_marginTop=”37dp” android:layout_centerHorizontal=”true” android:height=”30dp” android:width=”50dp” android:background=”#ff76ffa6″ /> <TextView android:layout_width=”wrap_content”
android:layout_height=”wrap_content” android:text=”Enter the number1″ android:id=”@+id/textView2″ android:layout_alignTop=”@+id/editText” cseitquestions.blogspot.in cseitquestions.blogspot.in
android:layout_alignParentLeft=”true” android:layout_alignParentStart=”true” android:layout_alignBottom=”@+id/editText” /> <TextView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Enter the number2″ android:id=”@+id/textView3″ android:layout_below=”@+id/textView2″ android:layout_alignParentLeft=”true” android:layout_alignParentStart=”true” android:layout_marginTop=”31dp” /> <EditText android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@ +id/editText2″ android:layout_alignTop=”@+id/ textView3″ android:layout_alignLeft=”@+id/editText” android:layout_alignStart=”@+id/editText” android:width=”50dp” android:height=”30dp” android:background=”#ff6fffab” /> <Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Add” android:id=”@+id/button” android:layout_below=”@+id/editText2″ android:layout_alignRight=”@+id/editText2″ android:layout_alignEnd=”@+id/editText2″ android:layout_marginTop=”45dp” /> <TextView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:textAppearance=”?android:attr/textAppearanceMedium” android:text=”Result” android:id=”@+id/textView4″ android:layout_below=”@+id/button” android:layout_alignRight=”@+id/editText2″ android:layout_alignEnd=”@+id/ editText2″ android:layout_marginTop=”85dp” />
</RelativeLayout> cseitquestions.blogspot.in cseitquestions.blogspot.in MainActivity.java public class MainActivity extends Activity implements OnClickListener
{ Button button; EditText editText; EditText editText2; TextView textView4; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = (Button) findViewById(R.id.button); editText = (EditText) findViewById(R.id.editText); editText2 = (EditText) findViewById(R.id.editText2); textView4 = (TextView) findViewById(R.id.textView4); button.setOnClickListener(this); } public void onClick(View view) { int a,b,c; a=Integer.parseInt(editText.getText().toString()); b=Integer.parseInt(editText2.getText().toString()); c=a+b; textView4.setText(“The result is “+c); } }
Output
Intents
Actually intents are not one of android application components; but used for activating components in Android. It is the part of core message system in android. It defines a message to activate the target component. For example, if we want to invoke a new activity from our current activity, then we need to fire an intent specifying the new activity. Further if we want to start another application from our activity, then also we require intent.
Intent is a messaging object that can be used to request an action from another app component. Although intents facilitate communication between components in several ways, there are three fundamental use-cases:
- Activity
- Service
- Broadcast
Starting activities We may want to start another activity from the existing one either as a new activity on top of the activity stack or as a result back from the previous one. For example, if we start an activity which allows the user to pick a person from a list of
contacts, it returns the person that was selected when selection completed i.e end of previous activity.
- startActivity(Intent)
- startActivityForResult(Intent, int)
The startActivity(Intent) method is used to start a new activity, which will be placed at the top of the activity stack. It takes a single argument, an Intent, which describes the activity to be executed. Sometimes we may want to get a result back from an activity when it ends.
Types of Intents: Intents have been classified into two types. They are
- Explicit Intents
- Implicit Intents
1) Explicit Intents:
Explicit intent is called for internal communication of an application. It is being invoked by mentioning the target component name. The component or activity can be specified which should be active on receiving the intent. For this reason mostly it is used for intra application communication. The following code describes the way of creating an explicit intent. While creating explicit intent, the target activity is specified so that the android system will invoke the activity.
Now the addition of two numbers program has been modified in order to use intent. In the first activity, inside the onClick() method intent object is created. While creating intent object the target component is specified that should be get activated. Here the MainActivity2 is the target activity that will be invoked by this intent. Since intents are part of the core message system of android, data is passed to the second activity
‗MainActivity2‘. i.e. input numbers are read in the first activity, when the button is clicked intent object is created and the result is passed through the intent object. It will activate the target activity. We will get the result in the second activity. The code for second activity is given below.
The second activity is activated by the intent object. Also the second activity receives data or message from the first activity through intent object. The Bundle class is used to save the activity state. So data from the intent object is read with the help of Bundle. The getIntent() method will retrieve data from the intent object. Intent can have the following information.
- Component name – The name of the component to start. This is optional, but it’s the criticalpiece of information that makes an intent explicit, meaning that the intent should be delivered
only to the app component defined by the component name. Without a component name, the intent is implicit and the system decides which component should receive the intent based on the other intent information (such as the action, data, and category).
- Action – A string that specifies the generic action to perform (such as view or pick). Somecommon actions for starting an activityare:
- ACTION_VIEW – This action is used in an intent with startActivity() when it has
some information that an activity can show to the user, such as a photo to view in a gallery app, or an address to view in a map app.
- ACTION_SEND – Also known as the “share” intent, this intent is used with startActivity() when some data that the user can share through another app, such as an email app or social sharing
- Data – The URI (a Uri object) that references the data to be acted on and/or the MIME type ofthat data. The type of data supplied is generally dictated by the intent’s action. For example, if the action is ACTION_EDIT, the data should contain the URI of the document to
- Categories – A string containing additional information about the kind of component thatshould handle the
- Extras – Key-value pairs that carry additional information required to accomplish therequested action.
- Flags – Flags defined in the Intent class that function as metadata for the intent. Theflags may instruct the Android system how to launch an
2) Implicit Intents:
When implicit intents are used, a message is sent to the android system to find an appropriate activity to respond to the intent. For example, to share a video, we can use intent. The video can be shared through any type of external application. To do this we can use intent. When intent is received, android system will invoke an activity which is capable
of sending video. If there is more than one activity is capable of receiving the intent, the android system will present a chooser so that the user can select which activity or application should handle it. The following sample code shows the use of implicit intents.
GUI Components Basics of User Interface
App‘s user interface is everything that the user can see and interact with. Android provides a variety of pre-build UI components such as structured layout objects and UI controls that allow us to build the graphical user interface for our app. Android also provides other UI modules for special interfaces such as dialogs, notifications, and menus. All user interface elements in an android app are built using View and ViewGroup objects. A View is an object that draws something on the screen that the user can interact with. A ViewGroup is an object that holds other View (and ViewGroup) objects in order to define the layout of the interface. All UI controls have attributes and id. Attributes are used to specify values for the property of a UI control. The id for a UI control is used for referring the controls. Attributes Every View and ViewGroup object supports their own variety of XML attributes. Some attributes are specific to a View object (for example, TextView supports the textSize attribute), but these attributes are also inherited by any View objects that may extend this class. Some are common to all View objects, because they are inherited from the root View class (like the id attribute). And, other attributes are considered “layout parameters” which are attributes that describe certain layout orientations of the View object, as defined by that object’s parent ViewGroup object. ID Any View object may have an integer ID associated with it, to uniquely identify the View within the tree. When the application is compiled, this ID is referenced as an integer, but the ID is typically assigned in the layout XML file as a string, in the id attribute. This is an XML attribute common to all View objects (defined by the View class) and you will use it very often. The syntax for an ID, inside an XML tag is:
Input Controls
android:id=”@+id/my_button”
Input controls are the interactive components in our app’s user interface. Android provides a wide variety of controls we can use in our UI, such as buttons, text fields, seek bars, checkboxes, zoom buttons, toggle buttons etc.
Common Controls
Android provides more controls but only few are listed here. To explore other controls browse the android.widget package. If our app requires a specific kind of input control, we can build our own custom components.
Introduction
The commonly used controls have been discussed. There are various controls available under android.widget package. Few controls have been covered here. EdiText We can add a text box control to our app by adding EditText control called EditTextName in the layout file. This EditText control called EditTextEmail acts as a form field for the user‘s email address.
The following code shows the edit text control added to the layout xml file. The edit text control has a property called android:inputType . It provides advantage for users to set the type of input we want to receive in the text box. The value for the input type property can be any of the valid property values such as text, number, password, email etc.
- Stage a1 (apply) Lab Activities:
Running the GUI Components, Fonts, Colors App
GUI Components and colours
The following program illustrates the GUI Components and Colours for Android App
Step 1: Design
- Open the actual Project folder(app) in Android Studio IDE
- Click res directory -> layout -> xml -> Design
- Insert the GUI components to Design view in xml
- Step 2: Open res directory -> layout ->Enter the id for each component
activity_main.xml and add following code
<?xml version=”1.0″ encoding=”utf-8″?>
<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:paddingLeft=”@dimen/ activity_horizontal_margin” android:paddingRight=”@dimen/activity_horizontal_margin” android:paddingTop=”@dimen/activity_vertical_margin” android:paddingBottom=”@dimen/activity_vertical_margin” tools:context=”.MainActivity”>
<TextView android:layout_width=”match_parent” android:layout_height=”wrap_content” android:text=”GUI Components” android:id=”@+id/t1″ android:layout_alignParentTop=”true” android:layout_alignParentEnd=”false” android:layout_alignParentStart=”false” android:autoText=”false” android:minHeight=”40dp” android:textStyle=”bold” android:textSize=”30dp” android:textIsSelectable=”false” android:textAlignment=”center” android:textColor=”@color/accent_material_dark” />
<Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Green” android:id=”@+id/b1″ android:layout_alignTop=”@+id/b2″ android:layout_alignParentStart=”true” />
<Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Red” android:id=”@+id/b2″ android:layout_centerVertical=”true” android:layout_centerHorizontal=”true” />
Home Activities:
Activity 1:
In Android, just use “android.widget.Button” class to display a normal button.
In this tutorial, we show you how to display a normal button, add a click listener, when user click on the button, open an URL in your Android‟s internet browser.
P.S This project is developed in Eclipse 3.7, and tested with Android 2.3.3.
Note
For more advance function, like image, please refer to this ImageButton example and also this ImageButton selector example.