Android User Interface : Life cycles and Layouts


  Activity
  •  Creating Activity
  • Activity Lifecycle
  • Activity Lifetime
  • Starting Activity
  • Process Lifecycle
2. Layouts
  •  Creating Layout
  • Types of layout
  • Layout parameters

Activity:

  • An Activity presents a visual user interface for one focused endeavor the user can undertake.
  • Each Activity represents a screen (similar to the concept of a Form in desktop development) that an application can present to its users.
  • Most Activities are designed to occupy the entire display, but you can create Activities that are semi-transparent, floating (Activity working as a dialog).
Creating an Activity:

  •  Create a new Activity by extending the Activity class. 
  • Override the onCreate() method to set the view for the activity 
  • Set the user interface to an Activity using the setContentView method in the onCreate method of the Activity. 
  • Use the findViewById(int) method to retrieve the reference of the widgets in UI. 
  • The basic skeleton code for a new activity is shown below :
public class MyActivity extends Activity {
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
}
}


In order to use an Activity in the application, it should be registered in the
manifest with the <activity> tag.
<activity android:label=”@string/app_name”
android:name=”.MyActivity”>
<intent-filter>
<action android:name=”android.intent.action.MAIN” />
<category android:name=”android.intent.category.LAUNCHER” />
</intent-filter>
</activity>

  • Intent filter nodes within the activity tag, specify the Intents about the Activity will listen for and react to.
  • To make an Activity available from the main program launcher, it must include an Intent Filter listening for the Main action and the Launcher category.

Activity Life Cycle:


Activities in the system are managed as an activity stack.
  •  The Android memory manager uses this stack to determine the priority of applications based on their Activities when deciding which application to terminate to free resources.
  • An activity has essentially four states:
  • Active : An activity in the foreground of the screen.
  • Paused : An activity has lost focus but is still visible.
  • Stopped : An activity is completely obscured by another activity.
  • Inactive : After an Activity has been killed or before it has been launched.



Activity State Paths :

  • OnCreate(Bundle b) : Called when the activity is first created. Normal static setup is donehere. This method also provides you a Bundle containing the activity's previously frozen state, if there was one. 
  • OnRestart() : Called after the activity has been stopped, prior to it being restarted again. 
  • OnStart() : Called when the activity is becoming visible to the user. 
  • OnResume() : Called when the activity will start interacting with the user. At this point your activity is at the top of the activity stack, with user input going to it. 
  • OnPause() : Called activity is losing its focus but still visible in the background. used to commit unsaved cha nges to persistent storage. 
  • OnStop() : Called when the activity is no longer visible to the user. 
  • OnDestroy : Called before an activity is destroyed. 
  • onSaveInstanceState(Bundle) : Called before placing the activity in a background state,allowing to save away any dynamic instance state in the activity into the given Bundle, to be later received in onCreate(Bundle) if the activity needs to be re-created. 
  • onRestoreInstanceState(Bundle) : Called after onStart() when the activity is being reinitialized from a previously saved state. 
  • NOTE : An activity can be killed by the system when it is in either OnPause() or onStop() or OnDestroy() state.

Activity Life times:


Entire lifetime :
  •  Happens between the first call to onCreate(Bundle) through to a single final call to onDestroy(). An activity will do all setup of "global" state in onCreate(), and release all remaining resources in onDestroy().
Visible lifetime :
  • Happens between a call to onStart() until a corresponding call to onStop().D
  • During this time the user can see the activity on-screen, though it may not be in the foreground and interacting with the user.
Foreground lifetime :
  •  Happens between a call to onResume() until a corresponding call to onPause().

Starting Activities:


  • The startActivity(Intent) method is used to start a new activity, which will be placed at the top of the activity stack. 
  • startActivityForResult(Intent intent, int requestCode) method is used to start an activity and get back the result from the started activity when it ends. 
  • The result will come back through onActivityResult(int requestCode, int resultCode, Intent) method. 
  • When an activity exits, it can call setResult(int resultCode) to return data back to its parent.

Starting Activities and Getting results:


Example Code:
public class MyActivity extends Activity {
static final int PICK_CONTACT_REQUEST = 0;
protected boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
startActivityForResult(
new Intent(Intent.ACTION_PICK,newUri("content://contacts")),
PICK_CONTACT_REQUEST);
return true;
}
return false;
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PICK_CONTACT_REQUEST) {
if (resultCode == RESULT_OK) {
startActivity(new Intent(Intent.ACTION_VIEW, data));
}
}
}
}

Process Life Cycle:

  •  The Android system will need to remove the old processes when memory runs low. 
  • The decision about which process to remove is tied to the state of the user's interaction with it and is as follows:
                     1  The foreground activity is considered most important. Its process will only be
killed as a last resort.
                     2 A visible activity is considered extremely important and will not be killed unless that is required to keep the foreground activity running.
                     3 A background activity (a paused activity) is no longer critical, so the system may safely kill its process.
                    4 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.


Layouts:

  •  Layout is the design plan or the architecture for the user interface in an activity. 
  • Layout is required to arrange or organize the widgets inside an activity. 
  • Layout defines the activity structure & holds all the elements that are part of the user interface. 
  • Layouts can be nested.


Types of Layouts
  1.  Linear Layout: A layout that organizes its children into a single horizontal or vertical row.
  2. Table Layout: A layout that positions its children into rows and columns. 
  3. Relative Layout: A layout that allows to organize child elements in positions relative to the parent or siblings elements. 
  4. Frame Layout: It is designed to block out an area on the screen to display a single item.

Declaring Layout:


A Layout can be declared in two ways:
1  Declaring in XML:
  • Android provides a straightforward XML tags that corresponds to the View classes and subclasses, such as those for widgets and layouts that can be added to the layout. 
  • Instantiating at runtime: 
  • Your application can create View and ViewGroup objects (and manipulate their properties) programmatically.

Layout Example (XML)
 Example: [A linear layout with a text label and a button]
 <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:orientation="vertical" >
 <TextView android:id="@+id/text"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:text="Hello, I am a TextView" />
 <Button android:id="@+id/button"
 android:layout_width=" fill_parent"
 android:layout_height="wrap_content"
 android:text="Hello, I am a Button" />
 </LinearLayout>
 Set content view in onCreate() method as setContentView(R.layout.file.xml)


Layout code(Java)

Example: [A linear layout with a text label and a button]
 LinearLayout linLay = new LinearLayout(this);
 linLay.setOrientation(1);
 linLay.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT));
 TextView textView = new TextView(this);
 textView.setText("Hello, I am a TextView");
 textView.setId(TEXT_ID); //Pass some Constants
 textView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
 Button button = new Button(this);
 button.setText("Hello, I am a Button");
 button.setId(BUTTON_ID); //Pass some Constants
 button.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
 linLay.addView(textView);
 linLay.addView(button);
 setContentView(linLay);
 Set content view in onCreate() method as setContentView(linLay)



Command Attribute:


  • id : an XML attribute common to all View objects, Supplies an identifier name for a view.
 Syntax:
         android:id="@+id/my_button" //For a button
  •     The at symbol (@) at the beginning of the string indicates that the XML parser should parse and expand the rest of the ID string and identify it as an ID resource. 
  • The plus-symbol (+) means that this is a new resource name that must be created and added to the resources.
 Accessing View Object:

  •  Accessing a View object declared in XML programmatically. 
  • Access the element by its id text as given below.
For example: A button represents as
 <Button android:id="@+id/my_button"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text=“Submit"/>
 In java program :
 //Load the Layout using R class
 setContentView(R.layout.main));
 // Get reference to control
 Button myButton = (Button) findViewById(R.id.my_button);
 In XML :
 android:layout_below="@ id/my_button "

Layout parameters:


  • LayoutParams are used by views to tell their parents how they want to be laid out. 
  • The base LayoutParams class just describes how big the view wants to be for both width and height. 
  • XML layout attributes named layout_something define layout parameters for the View that are appropriate for the ViewGroup in which it resides.
 For example:
 layout_width
 layout_height
 layout_weight
 layout_below

Supported Parameters:
  •  ViewGroup.LayoutParams : (Common for all) 
  • layout_height and layout_width 
  • ViewGroup.MarginLayoutParams & FrameLayout.LayoutParams :(Common for all) 
  • layout_marginBottom, layout_marginLeft, layout_marginTop and layout_marginRight 
  • LinearLayout.LayoutParams & TableLayout.LayoutParams : layout_gravity and layout_weight
  •  RelativeLayout.LayoutParams :
            -->  layout_above, layout_alignBaseline, layout_alignBottom, layout_alignLeft,
layout_alignParentBottom, layout_alignParentLeft, layout_alignParentRight,
layout_alignParentTop, layout_alignRight, layout_alignTop, layout_alignWithParentIfMissing,
layout_below, layout_centerHorizontal, layout_centerInParent, layout_centerVertical,
layout_toLeftOf and layout_toRightOf

  • Position, Size and Padding:
1 Position – Position is the location of the view relative to its parent.
              Methods : getLeft(), getTop(), getRight(), getBottom
2 Size – The size of a view is expressed with width and height.
              Methods : getWidth(), getHeight(), getMeasuredHeight(), getMeasuredWidth()
3 Padding – Padding is used to offset the content of the view by a specific amount
of pixels.
              Methods : getPaddingLeft(), getPaddingRight(), getPaddingTop(),
getPaddingBottom()
 e.g.
 TextView disp = (TextView) findViewById(R.id.text);
 Button btn = (Button) findViewById(R.id.button);
 disp.setText(“Left:”+btn.getLeft()+” Width:”+btn.getWidth()+” Right
Padding:”+btn.getPaddingRight())






Comments

Popular posts from this blog

Android Objective type Question and Answers

Android Questions and Answers for written exams

Core Java -----Question and Answers