Professional Documents
Culture Documents
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.
TextView
ImageView
EditText
SearchView
BottomNavigationView
NavigationView
SurfaceView
RecyclerView
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" />
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.
Drawable resources are those images which are present in the drawable
folder of your application.
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=” “”
android:src="@drawable/your_new_image"
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
Email
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"/>
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.
SearchView Icon
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.
BottomNavigationView.OnNavigationItemSelectedListener
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.
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:
Navigation Drawer Application Preview
Opening the Navigation Drawer
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 – Instagram Camera Snapchat
Camera – SurfaceView
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
});
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"
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
</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
super.onCreate(savedInstanceState);
@Override
Bundle savedInstanceState) {
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:
<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" />
2. 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.
3. Create an adapter that extends the PagerAdapter class. Define all the
methods as per your functionality.
4. Finally, wire up the ViewPager in your activity by adding the following
code:
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 in WhatsApp
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>
1. To add tabs programmatically, you can write the following code in the
Activity’s Java File:
tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));
tabLayout.addTab(tabLayout.newTab().setText("Tab 3"));
2. 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>
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() {
MediaStore.MediaColumns._ID,
MediaStore.Images.Media.DATE_TAKEN
};
projection,
null,
null,
BUCKET_ORDER_BY
)) {
int idColumn =
cur.getColumnIndexOrThrow(MediaStore.Images.Media._ID);
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);
if (bundle ! = null) {
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);
editor.putInt(“data”, 2);
editor.commit();