Android UI Components – Core components of screen

Introduction to Android UI Components

In this post, we will understand the core Android UI components. Before building an Application, we have to know about the core android UI components of the screen which create the User Interface in Android.

Activity is a means by which users can interact easily with an application. Activity by itself does not have a presence on the screen. Instead, it has to draw the screen using Views and ViewGroups.

Here, we will learn the details about creating user interfaces in Android, how users interact with them.

Views and ViewGroups

A view is a widget that shows on screen. Examples of views are buttons, labels, and text boxes.

A view comes from the base class android.view.View.

We can see one or more than one views are grouped together into a single View Group.

A ViewGroup provides the layout in which you can order the appearance and sequence of views.

Examples of ViewGroups are LinearLayout and FrameLayout. A ViewGroup comes from the base class android.view.ViewGroup.

Android supports the following ViewGroups:

  • LinearLayout
  • AbsoluteLayout
  • TableLayout
  • RelativeLayout
  • FrameLayout
  • ScrollView

Let’s see some of them in detail.


The LinearLayout arranges views in a single column or a single row. Child views can be arranged either vertically or horizontally.

To see how LinearLayout works, consider the following elements typically contained in the main.xml file:

<LinearLayout xmlns:android=""

   android:text="@string/hello_world" />


In the main.xml file, observe that the root element is <LinearLayout> and it has a <TextView> element contained within it. The <LinearLayout> element controls the order in which the views contained within it appears.

Each View and ViewGroup has a set of common attributes:

layout_widthIt Specifies the width of the View or ViewGroup.
layout_heightIt Specifies the height of the View or ViewGroup
layout_marginTopIt Specifies extra space on the top side of the View or ViewGroup
layout_marginBottomIt Specifies extra space on the bottom side of the View or ViewGroup
layout_marginLeftIt Specifies extra space on the left side of the View or ViewGroup
layout_marginRightIt Specifies extra space on the right side of the View or ViewGroup
layout_gravityIt Specifies how child Views are positioned
layout_weightIt Specifies how much of the extra space in the layout should be allocated to the View
layout_xIt Specifies the x-coordinate of the View or ViewGroup
layout_yIt Specifies the y-coordinate of the View or ViewGroup


The RelativeLayout enables you to specify how child views are positioned relative to each other. Consider the following main.xml file:

   android:layout_width=”fill_parent” ​​​​
   xmlns:android=”” >

   android:layout_width=”wrap_content” ​​​​​​​​
android:layout_alignParentLeft=”true” />

   android:layout_centerHorizontal=”true” />

   android:layout_alignRight=”@+id/txtComments” />

<Button android:id=”@+id/btnCancel” ​​​​​​​​
   android:layout_width=”124px” ​​​​​​​​
   android:layout_height=”wrap_content” ​​​​​​​​
   android:layout_alignLeft=”@+id/txtComments” />


Notice that each view embedded within the RelativeLayout has attributes that enable it to align with another view.

These attributes are as follows:








The FrameLayout is a placeholder on the screen that we can use to display a single view. Views that you add to a FrameLayout are always anchored to the top left of the layout.

Consider the following content in main.xml:

<RelativeLayout android:id=”@+id/RLayout”
xmlns:android=”” >

android:layout_alignParentLeft=”true” />

android:layout_centerHorizontal=”true” >

android:layout_height=”wrap_content” />


Here, we have a FrameLayout within a RelativeLayout. Within the FrameLayout, we embed an ImageView.


A ScrollView is a special type of FrameLayout in which it enables users to scroll through a list of views that occupy more space than the physical display.

The ScrollView can contain only one child view or ViewGroup, which normally is a LinearLayout.

The following main.xml content shows a ScrollView containing a LinearLayout, which in turn contains some Button and EditText views:

android:layout_height=”fill_parent” ​​​​
xmlns:android=”” >

android:layout_width=”fill_parent” ​​​​​​​​
android:layout_height=”wrap_content” ​​​​​​​​
android:orientation=”vertical” >

android:id=”@+id/button1” ​​​​​​​​​​​​
android:layout_height=”wrap_content” ​​​​​​​​​​​​
android:text=”Button 1” />

android:id=”@+id/button2” ​​​​​​​​​​​​
android:layout_width=”fill_parent” ​​​​​​​​​​​​
android:text=”Button 2” />

android:layout_width=”fill_parent” ​​​​​​​​​​​​
android:text=”Button 3” />

android:id=”@+id/txt” ​​​​​​​​​​​​
android:layout_height=”300px” />

android:text=”Button 4” />

android:id=”@+id/button5” ​​​​​​​​​​​​
android:layout_width=”fill_parent” ​​​​​​​​​​​​
android:layout_height=”wrap_content” ​​​​​​​​​​​​
android:text=”Button 5” />


Android Intents and Intent Filters – Android Basics

Android Intents and Intent Filters

Android intent is an intention to perform an operation.  It is an abstract description of an operation to be performed. It can be used with startActivity() to launch an Activity, broadcastIntent() to send it to any interested BroadcastReceiver components, and startService(Intent) or bindService(Intent, ServiceConnection, int) to communicate with a background Service.

Although intents facilitate communication between components in several ways, there are three fundamental use cases:

Starting an activity

An Activity represents a single screen in an app. You can start a new instance of an Activity by passing an Intent to startActivity(). The Intent describes the activity to start and carries any necessary data.

Activity : StartActivity and StartActivityforResult.

Starting a Service

Service is a component that performs operations in the background without a user interface. Service : bindService / StartService

Delivering a broadcast

The system delivers various broadcasts for system events, such as when the system boots up or the device starts charging. To transfer data from one component to another (Custom objects can be transferred by implementing parcelable or Serializable interfaces).

Types of Intents:

Explicit Intent: It is an Intent which contains explicit information about a component which will be started using the intent, for example:

Intent intent = new Intent(this, TestActivity.class );
Intent intent = new Intent();
intent.setClassName("packagename", fully qualified class name)

Implicit Intent: It is an Intent which doesn’t specify component information explicitly, but “Action” is used to find the component, for example:

Intent intent  =  new Intent("Action");
Intent intent  =  new Intent();

Fields of Intent in Android:


It specifies the component to be started.

It can be set to class or fully qualified class name.


It is the context in which intent will be created.

For Activity: Context is “this”.

For ContentProvider: Context is getContext().

For Service: Context is getApplicationContext().

For BroadcastReceiver: Context will be passed as a parameter to onRecieve() method.


It is a String Constant which defines unique action performed by the intent (unique by its package name).


It is more information about an action.

By default, category is set to “android.intent.category.DEFAULT“.


It is a type of URI that supported in the component.

Example: Browser supports “http” URI, Telephone supports “tel” URI.

Context and Component are used for Explicit Intent and remaining fields are used for Implicit intent.

Intent Resolution:

To resolute intent Action, Data and Category are used for Implicit and Component is used for Explicit intent.

Resolution of Explicit Intent

Explicit intent can be resolved by Component name by creating an Object of required Class from required Package.

Resolution of Implicit Intent

To start a component with Implicit Intent it has to be registered with intent-filter.

Intent-filter filters intent based on following criteria:

1. If action/category/data is missing nothing will be checked.

2. If a category is set to default it will not be checked.

3. If intents action/category/data is not matching with intent-filters action/category/data, the intent is discarded.

4. If all parameters match the object of the component is created and launched.

Sticky Intent:

When we have to live the intent, an object of intent is live called Sticky-Intent.

      • Generally, OS use it at the situation where we have to broadcast every time.
      • We will not create every time object of intent by the use of Sticky-Intent.

Example: BatteryChanged, LocationChanged.

For this, we have not used any permission. It is only a feature i.e. managed by OS.

Android Fragment – Android Fragment Example | Fragment Lifecycle

The fragment is a small part of Activity. Android fragment splits the Activity into Sub Activity called Fragment that fits into an Activity.

This feature was first time introduced in Android 3.0 HoneyComb (API level 11).

There is no need to add any permissions inside the manifest file to create the fragment in your application.

It provides us a way to give a consistent UI that is optimized for a wide variety of Android devices, screen sizes etc.

We can also reuse the same fragment in different activities.

A single Activity can contain multiple fragments that’s why we say a Fragment is a type of Sub Activity.

Each fragment has its own lifecycle, which is closely related to the lifecycle of host Activity. So it means when our Activity is stopped then the fragments which are available in activity are also stopped.

Create Fragment class in your application

To create a Fragment in your application we have to extend its subclass with Fragment and override its methods.

public class MyFragment extends Fragment{

public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
// TODO Auto-generated method stub
return super.onCreateView(inflater, container, savedInstanceState);

Android Fragment Lifecycle

The following figure shows the Fragment Lifecycle. Let’s see the methods of Fragment in Android.

Android fragment
Fragment Lifecycle


This method is called when the fragment has been associated with the activity.


This method is called by the system when creating the android fragment. Within your implementation, you should initialize essential components of the fragment that you want to retain when the fragment is paused or stopped, then resumed.


The system calls this when it’s time for the android fragment to draw its user interface for the first time. To draw a UI for your fragment, you must return a View from this method that is the root of your fragment’s layout.


It is called when the activity’s onCreate() method has returned, also called when the fragment is being disassociated from the activity.


This method is called once the fragment gets visible.


The fragment is visible in the running activity.


The system calls this method as the first indication that the user is leaving the fragment.


The android fragment is not visible. Either the host activity has been stopped or the fragment has been removed from the activity but added to the back stack.


It is called when the view hierarchy associated with the fragment is being removed.


This method is called to do final cleanup of the fragment’s state but not guaranteed to be called by the Android platform.


It is called when the fragment is being disassociated from the activity.

Perform Fragment Transaction

We can use android fragment in our activity to add, remove, replace, and perform other actions with them in response to user interaction.

Each set of changes that you commit to the activity is called a transaction and you can perform on using APIs in FragmentTransaction.

You can acquire an instance of FragmentTransaction from the FragmentManager like this:

FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();


Android BroadcastReceiver – Create | Register examples

An Android BroadcastReceiver is another component in Android process, along with activities, content provider, and Services.

It is a component that can respond to a broadcast message sent by a client.

The message itself is an Android broadcast intent. A broadcast intent (message) can invoke more than one receiver.

A component such as an activity or a service uses the sendBroadcast() method available on the Context class to send a broadcast event.

Receiving components of the broadcast intent will need to inherit from a receiver class.

These receiving components need to be registered in the manifest file through a receiver tag to indicate that the class is interested in responding to a certain type of broadcast intent.

Create Android BroadcastReceiver class

public class MyReceiver extends BroadcastReceiver
  public void onReceive(Context context, Intent intent) {
  // TODO Auto-generated method stub

Register Android BroadcastReceiver

A receiver can be registered via the AndroidManifest.xml file.

Alternatively to this static registration, you can also register a receiver dynamically via the Context.registerReceiver() method.

The implementing class for a receiver extends the BroadcastReceiver class.

If the event for which the broadcast receiver has registered happens, the onReceive() method of the receiver is called by the Android system.

 <receiver android:name="MyReceiver">
      <action android:name="android.intent.action.BOOT_COMPLETED">

Registering and Unregistering Android Broadcast Receiver in Code:

private IntentFilter filter = new IntentFilter(MyReceiver.ACTION);
private MyReceiver receiver = new MyReceiver();

public void onResume()

 //Register the broadcast receiver.
 registerReceiver(receiver, filter);

public void onPause()
 //Unregister the receiver

System generated Events

Some system generated events are as follows:


It describes Sticky broadcast containing the charging state, level, and other information about the battery.


It Indicates low battery condition on the device.


This is broadcast one time after the system has finished booting.


It performs a call to someone specified by the data.


It describes the device is reboot.

Content Provider – Android Development Tutorials | Articles

The Content Provider provides content to the Android application. They are one of the primary building blocks of Android applications.

You need to use Content providers only if data needs to be shared between multiple applications. For example, the contacts information needs to be shared among multiple applications so it will require content providers.

Content providers encapsulate data and provide it to applications through the single ContentResolver interface.

Steps to create ContentProvider

  1. Create ContentProvider subclass (android.ContentProvider)
  2. Register ContentProvider in AndroidManifest.xml file using provider element. (<provider>).


To Register ContentProvider use following attributes:

  • android:name -> ContentProvider subclass name.
  • android:authorities -> authority used for ContentProvider
  • android:exported -> true/false (If true: ContentProvider can be used in other applications/ If false: Content provider is used only in local application)


The default value of android:exported is “true”.


URI stands for Universal Resource Identifier.

  1. URI is used to identify a ContentProvider uniquely in the current device.
  2. URI has a special format like Content://Authority/Path 


Format contents are explained below:

Content: It is the protocol used to communicate ContentProvider.

Authority: A unique identifier used to identify ContentProvider (generally Authority is the name of the package in which ContentProvider is registered).

Path: It is a unique string appears after authority which is used to identify the table used in operation.

We can create our own ContentProvider by creating the subclass of ContentProvider and extends with ContentProvider and using a database like SQLite database and its methods.

Some primary Content Provider methods are

onCreate():  This is called to initialize the provider.

query(Uri, String[], String, String[], String):  It returns data to the caller.

insert(Uri, ContentValues):  It inserts new data into the content provider.

update(Uri, ContentValues, String, String[]):  It updates existing data in the content provider.

delete(Uri, String, String[]):  It deletes data from the content provider.

getType(Uri):  It returns the MIME type of data to the content provider.

Declare the ContentProvider in AndroidManifest.xml file

          android:authorities="com.example.androidcontentproviderexample" >

Initialize ContentProvider and Database

public class StudentProvider extends ContentProvider{
	// fields for my content provider

static final String PROVIDER_NAME = "com.example.androidcontentproviderexample";
static final String URL = "content://" + PROVIDER_NAME + "/students";
static final Uri CONTENT_URI = Uri.parse(URL);
static final String ID = "id";
static final String NAME = "name";
static final String PHONE = "phone";
static final int STUDENTS = 1;
static final int STUDENTS_ID = 2;
DBHelper dbHelper;

Use URIMatcher class to know the type of URI, URIMatcher matches the patterns.

static final UriMatcher uriMatcher;
	uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
      uriMatcher.addURI(PROVIDER_NAME, "students", STUDENTS);
      uriMatcher.addURI(PROVIDER_NAME, "students/#", STUDENTS_ID);

Now further you can implement your methods in this class.