What will you learn?
In this article, we will be studying various components that are most commonly found in Android Apps. This is your cheat sheet to kickstart your android development knowledge. Learning about these components is mandatory for android development.
Each component will be accompanied by its code for basic implementation, and a reference to their official documentation.
The components in this article are broadly classified as follows:
- Views
- UI Components
- Utility
Contents
What are Views in Android?
Views are the building blocks for the visual component of the App. Whatever would be visible on the screen, is defined and managed through different types of Views.
The most commonly used views are:
- TextView
- ImageView
- EditText
- SearchView
- BottomNavigationView
- NavigationView
- SurfaceView
- RecyclerView
- FloatingActionButton
Now we will take each of these views and see how to implement it and where is it used.
TextView in Android
Perhaps one of the most common views is TextView. TextView is used to display text on the screen. To add a TextView to your Activity, you simply need to add the following lines of code in the XML file:
<TextView android:id="@+id/text_view" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="Hello" />
We need to make a reference this in our Java file. If we want to access or modify it through code, we can do that by writing the following:
TextView textView = findViewById(R.id.text_view);
The text of this TextView can be changed in 2 ways:
- Modifying the android:text attribute in the XML file.
android:text=”Modified Text”
- Using the setText() function in the Java File.
textView.setText(“Modified Text”);
ImageView in Android
ImageViews are used to display images on the screen. The images could be Bitmap images or Drawable resources.
To add an ImageView to your Activity, add the following code in your XML file:
<ImageView android:id="@+id/image_view" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/my_image" />
For this code, our image is present in the Drawable folder, and it is given by the attribute “android:src=” “”
We need to make a reference of this in our Java file before we can use it for coding. If we want to access or modify it through code, we can do that by writing the following:
ImageView imageView = findViewById(R.id.image_view); //reference
We can change the image in 2 ways:
- Modifying the android:src attribute in the XML file.
android:src="@drawable/your_new_image"
- Using the setImageBitmap() or setImageDrawable() function in the Java File.
imageView.setImageDrawable(getResources().getDrawable(R.drawable.your_new_image));
The image you want to change it to should be present in the drawable folder. In this case, we are changing “my_image” to “your_new_image”.
EditText in Android
EditText is used to take input from the user. The input types supported are:
- Plain Text
- Datetime
- Multi-Line
- Numeric
- Phone Numbers
- Password (Text and Numeric)
- Addresses
To add an EditText to your Activity, write the following in your XML file:
<EditText android:id="@+id/input" android:layout_height="wrap_content" android:layout_width="match_parent" android:inputType="text"/>
This EditText will take Plain Text as input, as specified in the android:inputType attribute.
To get the text entered by the user, write the following code:
EditText input = findViewById(R.id.input); String str = input.getText().toString();
SearchView in Android
SearchView is used to give the user an interface to submit a search query. It acts as a simple EditText, and it needs to be configured by the developer to act as a search interface. Android also provides a fully functional search interface called Search Dialog. That handles all events by default and submits the appropriate search query.
The SearchView is represented as an icon which expands into an EditText after clicking by default.
To change this behaviour, set the android:iconifiedByDefault attribute to false, in the XML file.
To add a SearchView into your Activity, include the following code in your XML file:
<SearchView android:id="@+id/searchView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:queryHint="Search" />
You can read additional documentation about SearchView for more in-depth knowledge.
BottomNavigationView in Android
You might have noticed a bar at the bottom of many apps. This bar contains some icons which navigate to different screens of the app when clicked.
This bar is called the Bottom Navigation Bar. The BottomNavigationView widget is used to add a Bottom Navigation Bar. This allows users to switch between different views on clicking different icons. This is a Material Design Component, meaning that it is a functional design component, made by Google’s design library.
As per the Material Design guidelines, the bar should be used for:
- Destinations/Screens that need to be accessible from anywhere inside the app
- 3 to 5 destinations only
- Mobile or Tablet only
To use BottomNavigationView in your app, you need to follow four steps:
- Include the material design dependency in your app-level build.gradle file
- Add the BottomNavigationView widget in your MainActivity
- Define a menu resource file for populating the bar
- Define the actions that would be performed for each item, using the
BottomNavigationView.OnNavigationItemSelectedListener
Fortunately, Android Studio provides a template for BottomNavigationView that has all the above steps already done. You just need to modify the menu file and the Java Code as per your app’s functionality.
Let’s see an example using the template.
- Create a new project in Android Studio and select the Bottom Navigation Activity.
- Click Next. Enter a project name of your choice, and then click Finish.
- Android Studio will create a new application. After the build has finished, you can check out the MainActivity, and the other boilerplate code.
- Let’s test the generated app. Click the Run button. You will see an output similar to this:
NavigationView in Android
You might have observed a menu that opens up when you click an icon on the top-left side. This is called Left Navigation or Navigation Drawer.
Left Navigation can be implemented using the NavigationView. NavigationView is a scrollable view that is used to display a menu as a vertical list. It also contains a header view above the menu. It is also a Material Design Component.
To use NavigationView in your app, you need to follow four steps:
- Include the material design dependency in your app-level build.gradle file
- Add the NavigationView widget in your MainActivity
- Define a menu resource file and a layout file for the header.
- Define the actions that would be performed for each menu item, using the
NavigationView.setNavigationItemSelectedListener.
Android Studio has a template for the Navigation Drawer that has all these steps already done. You just need to modify the header layout, the menu resource file and the Java code for handling the actions.
Let’s see an example using the template.
- Create a new project in Android Studio and select the Navigation Drawer Activity.
- Click Next. Enter a project name of your choice, and then click Finish.
- Android Studio will create a new application. After the build has finished, you can check out the MainActivity, and the other boilerplate code.
- Let’s test the generated app. Click the Run button. You will see an output similar to this:
SurfaceView in Android
In Android, all simple layout views are all drawn on the same UI thread, which is also used for all user interaction. So, if we need to update UI rapidly, or if the rendering takes too much time and affects user experience, then we should use SurfaceView.
For example, if we need to have our own implementation of a Camera in our app, like in Snapchat and Instagram where there are different filters which change the face accordingly, we should use SurfaceView, as embedding a Camera directly into the layout will slow down all the other processes in the app.
SurfaceView provides a dedicated drawing surface embedded inside of a view. You can control the format of this surface and, its size; the SurfaceView takes care of placing the surface at the correct location on the screen.
The documentation for SurfaceView has a lot more information that you should read about.
RecyclerView in Android
In almost every other app, we can observe a list of items. For example, WhatsApp has a list of chats, Instagram has a list of posts, and Gmail has a list of emails. Although all of them are lists, the structure of their individual items is very different from each other.
RecyclerView enables the developer to create customised lists. It gives you the flexibility to define your own structure for the items and how the individual components in the list item (images, text, buttons, etc.) respond to events. Also, it handles large data sets efficiently.
To add a RecyclerView to an Activity, we need to do the following:
- Add the dependency for the support library required for RecyclerView. You can do it manually as well as automatically by dragging and dropping the RecyclerView widget into the layout.
- Create a layout file for the list item. This file should contain the structure of the individual item of the list.
- Create an Adapter class for the RecyclerView. An adapter is used for wiring up the functionality of the RecyclerView. It populates the list with the layout and the data you provide.
- Finally, reference the RecyclerView widget and the adapter in the Activity’s Java File and attach the adapter to the widget.
Here’s the official documentation for RecyclerView.
FloatingActionButton in Android
FloatingActionButton is a type of Button that is used to represent the primary action of the screen. It appears in front of all the screen content, usually in a circular shape, which gives the illusion of ‘floating’, hence the name. You might have observed it on WhatsApp as the new chat button, and on Gmail as compose email button.
It is also a Material Design Component. There are three requirements that a Floating Action Button should fulfil:
- Represent the primary action on a screen.
- Perform a constructive action (such as create, share, or explore).
- Be relevant to the screen on which it appears.
To add this component to your Activity, write the following code in the XML file:
<com.google.android.material.floatingactionbutton.FloatingActionButton android:id="@+id/fab" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="end|bottom" android:src="@drawable/ic_my_icon" android:layout_margin="16dp" />
To wire up the FAB, add the following code to your Activity’s Java File:
FloatingActionButton fab = findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //Add your action here } });
What are UI Components in Android?
In this classification, we have those classes/components that manipulate the UI in different ways to perform various actions. The most commonly used UI components are:
- Fragments
- ViewPager
- TabLayout
Fragments in Android
Fragments are reusable functional components that have their own layout and lifecycle. However, they cannot exist independently. They have to be a part of an activity.
You can think of a fragment as a portion of an activity, which has its own lifecycle, receives its own input events, and which you can add or remove while the activity is running (sort of like a “sub-activity” that you can reuse in different activities).
A fragment’s lifecycle is directly affected by its parent activity’s lifecycle. For example, when the activity is paused, all the fragments in it get paused, and when the activity is destroyed, all the fragments in it get destroyed. However, when the activity is in running state, you can manipulate each fragment independently, like add, remove or replace fragments. All of these operations are called transactions.
Read more: https://developer.android.com/guide/components/fragments
Fragments are used in BottomNavigationView, NavigationView and ViewPager (discussed below) to create the different screens. These are suitable for creating these screens as they are lightweight, and can be easily replaced as and when required.
Adding Fragment to an Activity
To add a fragment to an activity, write the following in the Activity’s XML file (manipulate the attributes as per your design):
<fragment android:name="com.example.myapp.BlankFragment" android:id="@+id/blank" android:layout_width="wrap_content" android:layout_height="match_parent" />
Now, we need to create a layout file as well as the Java file for the fragment. This can be done manually, or we can create a Fragment class using the Android Studio dialogue, and it will auto-generate these files for us.
Doing this manually, create a layout resource file in the res/layout folder. Name the file as fragment_blank.xml. Write the following code:
<FrameLayout 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:background="#F5F5DC" tools:context=" com.example.myapp.BlankFragment "> <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:text="Hello blank fragment!" /> </FrameLayout>
Now, create a Java file named BlankFragment.java. Write the following code:
package com.example.myapp; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class BlankFragment extends Fragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); }
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_blank, container, false); } }
No need to modify the MainActivity.java file. Run the app. You should see the text “Hello blank fragment!” wherever you placed the fragment widget in the Activity’s XML file.
ViewPager in Android
ViewPager is a widget that allows the user to swipe left and right between multiple pages of data. It can be used for a variety of actions that require swiping between components. It is most commonly used with Fragments as its pages.
Just like the RecyclerView, ViewPager also requires an adapter that determines how and which page is to be loaded. This adapter is known as the PagerAdapter.
Steps to implement a ViewPager in your activity:
- Add the following code to your activity’s XML file.
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/pager" android:layout_width="match_parent" android:layout_height="match_parent" />
- Create a layout resource file for the individual page layout. This file will define how each page would be structured. Most commonly, fragments are used, but it could be anything, even a simple ImageView.
- Create an adapter that extends the PagerAdapter class. Define all the methods as per your functionality.
- Finally, wire up the ViewPager in your activity by adding the following code:
ViewPager mPager = (ViewPager) findViewById(R.id.pager); MyAdaper adapter = new MyAdapter(); //Where MyAdapter is the adapter class defined by you mPager.setAdapter(adapter);
TabLayout in Android
You might have observed some tabs on WhatsApp that help to switch between different screens, like chats, status and calls. This functionality is implemented using TabLayout.
TabLayout provides a horizontal layout to display tabs, which can change the screen either by swiping or clicking on one of the tabs. To add a TabLayout to your activity, add the following code to your activity:
<com.google.android.material.tabs.TabLayout android:layout_height="wrap_content" android:layout_width="match_parent"> </com.google.android.material.tabs.TabLayout>
Tabs can either be added programmatically or can be hardcoded in the layout itself.
- To add tabs programmatically, you can write the following code in the Activity’s Java File:
TabLayout tabLayout = findViewById(R.id.tabLayout); tabLayout.addTab(tabLayout.newTab().setText("Tab 1")); tabLayout.addTab(tabLayout.newTab().setText("Tab 2")); tabLayout.addTab(tabLayout.newTab().setText("Tab 3"));
- To do the same through the layout file, you can write the following:
<com.google.android.material.tabs.TabLayout android:layout_height="wrap_content" android:layout_width="match_parent"> <com.google.android.material.tabs.TabItem android:text="@string/tab_text"/> <com.google.android.material.tabs.TabItem android:icon="@drawable/ic_android"/> </com.google.android.material.tabs.TabLayout>
TabLayout can also be used with ViewPager. You can call setupWithViewPager(ViewPager) to link the two together. This layout will be automatically populated from the PagerAdapter’s page titles.
Read more: https://developer.android.com/reference/com/google/android/material/tabs/TabLayout
What are Utility Components in Android?
These are the classes/functions that are used to perform essential tasks in the background. They are not visible in the frontend as such, but their functions bring about a change in the frontend. Some commonly used components are:
- ContentResolver
- Intent
- SharedPreferences
ContentResolver in Android
Many times, we need to access some of the user’s data, such as pictures, videos, contacts, files etc. Android does not provide direct access to the whole storage, as it can give rise to many security threats. Android provides an abstract class called ContentResolver that helps to fetch the above-mentioned content securely.
There are two main classes for exchange of data between different apps in the device: ContentProvider and ContentResolver. As the name suggests, ContentProvider provides the content to the ContentResolver, which helps in the exchange of data securely, as no direct access is provided.
As an example, let’s see how to get the paths of all the images present on the device.
Write the following code wherever you want to fetch the images:
private List<Uri> getAllImagePaths() { List<Uri> paths = new ArrayList<>(); String[] projection = new String[] { MediaStore.MediaColumns._ID, MediaStore.Images.Media.DATE_TAKEN }; Uri images = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; String BUCKET_ORDER_BY = MediaStore.Images.Media.DATE_TAKEN + " DESC"; try(Cursor cur = getApplicationContext().getContentResolver().query(images, projection, null, null, BUCKET_ORDER_BY )) { int idColumn = cur.getColumnIndexOrThrow(MediaStore.Images.Media._ID); if (cur != null && cur.moveToFirst()) { do { long id = cur.getLong(idColumn); Uri contentUri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id); paths.add(contentUri); } while (cur.moveToNext()); cur.close(); } } return paths; }
The list returned by this function will contain the Uri of each image present on the device. You can use a RecyclerView of images to load all these images.
Intent in Android
Intent is used for various tasks like switching between activities, communicating with Broadcast Receivers or background services. Its most common use is to launch a new Activity from an existing Activity. It can be done using the startActivity() method. We have a detailed post explaining how we start a new activity with an intent which will help in better understanding.
Switching Between Activities Using Intent
Suppose we want to go from MainActivity to NewActivity. We will write the following code in the MainActivity.java file:
startActivity(new Intent(MainActivity.this, NewActivity.class));
Intents can also be used to pass data between activities. Suppose we want to pass some integer value from MainActivity to NewActivity. We will write the following code in the MainActivity.java file:
Intent intent = new Intent(MainActivity.this, NewActivity.class); Intent.putExtra(“key”, 1); startActivity(intent);
Now, in the NewActivity.java file, write the following code:
Bundle bundle = getIntent().getExtras(); if (bundle ! = null) { int value = bundle.getInt("key"); }
In our note-taking application tutorial, we use intent to pass data from one activity to another. Take a look at it for a real-life example of it.
SharedPreferences in Android
Sometimes we need to store some data in the form of key-value pairs. For example, we might need to save a search query for future use, or user’s data so that the user stays logged in even after exiting the app. SharedPreferences allows us to do exactly that. It offers a variety of modes, including the private mode to store data privately.
Read more: https://developer.android.com/training/data-storage/shared-preferences
SharedPreferences Example
To write some integer data to SharedPreferences, write the following code:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPref.edit(); editor.putInt(“data”, 2); editor.commit();
To retrieve this data, write the following:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE); int data = sharedPref.getInt(“data”);
Again, in our note-taking app tutorial, we are using shared preferences to store the notes in the device’s storage. Please take a look at it.
Where to go from here?
We have studied the most common components that are used in everyday apps. This list is a cheat sheet for an android developer.
For you to learn how to develop Android applications, it is extremely important to get the basics cleared up.