Buttons

Android Button represents a push-button. The android.widget.Button is a subclass of TextView class and CompoundButton is the subclass of Button class.

There are different types of buttons in android such as RadioButton, ToggleButton, CompoundButton etc.

<Button  

        android:id=”@+id/button”  

        android:layout_width=”wrap_content”  

        android:layout_height=”wrap_content”  

        android:layout_below=”@+id/editText2″  

        android:layout_centerHorizontal=”true”  

        android:layout_marginTop=”109dp”  

        android:text=”ADD”  

        tools:layout_editor_absoluteX=”148dp”  

        tools:layout_editor_absoluteY=”266dp” />  

Checkboxes

Android CheckBox is a type of two state button either checked or unchecked.

There can be a lot of usage of checkboxes. For example, it can be used to know the hobby of the user, activate/deactivate the specific action etc. Android CheckBox class is the subclass of CompoundButton class. The android.widget.CheckBox class provides the facility of creating the CheckBoxes.

Methods of CheckBox class

There are many inherited methods of View, TextView, and Button classes in the CheckBox class. Some of them are as follows:

MethodDescription
public boolean isChecked()Returns true if it is checked otherwise false.
public void setChecked(boolean status)Changes the state of the CheckBox.

<CheckBox  

        android:id=”@+id/checkBox”  

        android:layout_width=”wrap_content”  

        android:layout_height=”wrap_content”  

        android:layout_marginLeft=”144dp”  

        android:layout_marginTop=”68dp”  

        android:text=”Pizza”  

        app:layout_constraintStart_toStartOf=”parent”  

        app:layout_constraintTop_toTopOf=”parent” /> 

Radio Buttons

RadioButton is a two state button which is either checked or unchecked. If a single radio button is unchecked, we can click it to make a checked radio button. Once a radio button is checked, it cannot be marked as unchecked by the user.

RadioButton is generally used with RadioGroup. RadioGroup contains several radio buttons, marking one radio button as checked makes all other radio buttons as unchecked.

<RadioButton  

        android:id=”@+id/radioButton1″  

        android:layout_width=”fill_parent”  

        android:layout_height=”wrap_content”  

        android:layout_gravity=”center_horizontal”  

        android:text=”Radio Button 1″  

        android:layout_marginTop=”20dp”  

        android:textSize=”20dp” />  

Toggle Buttons

Android Toggle Button can be used to display checked/unchecked (On/Off) state on the button. It is beneficial if users have to change the setting between two states. It can be used for On/Off Sound, Wifi, Bluetooth etc. Since Android 4.0, there is another type of toggle button called switch that provides slider control. Android ToggleButton and Switch both are the subclasses of CompoundButton class. ToggleButton class provides the facility of creating the toggle button.

XML Attributes of ToggleButton class

The 3 XML attributes of the ToggleButton class.

XML AttributeDescription
android:disabledAlphaThe alpha to apply to the indicator when disabled.
android:textOffThe text for the button when it is not checked.
android:textOnThe text for the button when it is checked.

Methods of ToggleButton class

The widely used methods of the ToggleButton class are given below.

MethodDescription
CharSequence getTextOff()Returns the text when the button is not in the checked state.
CharSequence getTextOn()Returns the text for when the button is in the checked state.
void setChecked(boolean checked)Changes the checked state of this button.

<ToggleButton  

        android:id=”@+id/toggleButton”  

        android:layout_width=”wrap_content”  

        android:layout_height=”wrap_content”  

        android:layout_marginLeft=”8dp”  

        android:layout_marginTop=”80dp”  

        android:text=”ToggleButton”  

        android:textOff=”Off”  

        android:textOn=”On”  

        app:layout_constraintEnd_toStartOf=”@+id/toggleButton2″  

        app:layout_constraintStart_toStartOf=”parent”  

        app:layout_constraintTop_toTopOf=”parent” /> 

Spinners

Android Spinner is like the combobox of AWT or Swing. It can be used to display the multiple options to the user in which only one item can be selected by the user.

Android spinner is like the drop down menu with multiple values from which the end user can select only one value. Android spinner is associated with AdapterView. So you need to use one of the adapter classes with a spinner. Android Spinner class is the subclass of AsbSpinner class.

<Spinner  

        android:id=”@+id/spinner”  

        android:layout_width=”149dp”  

        android:layout_height=”40dp”  

        android:layout_marginBottom=”8dp”  

        android:layout_marginEnd=”8dp”  

        android:layout_marginStart=”8dp”  

        android:layout_marginTop=”8dp”  

        app:layout_constraintBottom_toBottomOf=”parent”  

        app:layout_constraintEnd_toEndOf=”parent”  

        app:layout_constraintHorizontal_bias=”0.502″  

        app:layout_constraintStart_toStartOf=”parent”  

        app:layout_constraintTop_toTopOf=”parent”  

        app:layout_constraintVertical_bias=”0.498″ />

Input Events

Events are a useful way to collect data about a user’s interaction with interactive components of Applications. Like button presses or screen touch etc. The Android framework maintains an event queue as a first-in, first-out (FIFO) basis. You can capture these events in your program and take appropriate action as per requirements.

There are following three concepts related to Android Event Management −

  • Event Listeners − An event listener is an interface in the View class that contains a single callback method. These methods will be called by the Android framework when the View to which the listener has been registered is triggered by user interaction with the item in the UI.
  • Event Listeners Registration − Event Registration is the process by which an Event Handler gets registered with an Event Listener so that the handler is called when the Event Listener fires the event.
  • Event Handlers − When an event happens and we have registered an event listener for the event, the event listener calls the Event Handlers, which is the method that actually handles the event.

Event Listeners & Event Handlers

Event HandlerEvent Listener & Description
onClick()OnClickListener()This is called when the user either clicks or touches or focuses upon any widget like button, text, image etc. You will use onClick() event handler to handle such an event.
onLongClick()OnLongClickListener()This is called when the user either clicks or touches or focuses upon any widget like button, text, image etc. for one or more seconds. You will use the onLongClick() event handler to handle such an event.
onFocusChange()OnFocusChangeListener()This is called when the widget loses its focus ie. user goes away from the view item. You will use the onFocusChange() event handler to handle such an event.
onKey()OnFocusChangeListener()This is called when the user is focused on the item and presses or releases a hardware key on the device. You will use onKey() event handler to handle such an event.
onTouch()OnTouchListener()This is called when the user presses the key, releases the key, or any movement gesture on the screen. You will use onTouch() event handler to handle such an event.
onMenuItemClick()OnMenuItemClickListener()This is called when the user selects a menu item. You will use onMenuItemClick() event handler to handle such an event.
onCreateContextMenu()onCreateContextMenuItemListener()This is called when the context menu is being built(as the result of a sustained “long click)

Event Listeners Registration

Event Registration is the process by which an Event Handler gets registered with an Event Listener so that the handler is called when the Event Listener fires the event. Though there are several tricky ways to register your event listener for any event.

Touch Mode

Users can interact with their devices by using hardware keys or buttons or touching the screen.Touching the screen puts the device into touch mode. The user can then interact with it by touching the on-screen virtual buttons, images, etc.You can check if the device is in touch mode by calling the View class’s isInTouchMode() method.

Focus

A view or widget is usually highlighted or displays a flashing cursor when it’s in focus. This indicates that it’s ready to accept input from the user.

  • isFocusable() − it returns true or false
  • isFocusableInTouchMode() − checks to see if the view is focusable in touch mode. (A view may be focusable when using a hardware key but not when the device is in touch mode)

android:foucsUp=”@=id/button_l”

Menus

In android, Menu is an important part of the UI component which is used to provide some common functionality around the application. With the help of the menu, users can experience a smooth and consistent experience throughout the application. In order to use the menu, we should define it in a separate XML file and use that file in our application based on our requirements. Also, we can use menu APIs to represent user actions and other options in our android application activities.

To create the menu directory just right-click on the res folder and navigate to res->New->Android Resource Directory. Give resource directory name as menu and resource type also menu. one directory will be created under the res folder. 

To create an xml resource file simply right-click on the menu folder and navigate to New->Menu Resource File. Give the name of the file as menu_example. One menu_example.xml file will be created under the menu folder.

  • <menu> It is the root element that helps in defining Menu in an XML file and it also holds multiple elements.
  • <item> It is used to create a single item in the menu. It also contains nested <menu> elements in order to create a submenu.
  • <group> It is optional and invisible for <item> elements to categorise the menu items so they can share properties like active state, and visibility.

Android Different Types of Menus

In android, we have three types of Menus available to define a set of options and actions in our android applications. The Menus in android applications are the following:

  • Android Options Menu
  • Android Context Menu
  • Android Popup Menu

Android Options Menu is a primary collection of menu items in an android application and is useful for actions that have a global impact on the searching application. 

Android Context Menu is a floating menu that only appears when the user clicks for a long time on an element and is useful for elements that affect the selected content or context frame. 

Android Popup Menu displays a list of items in a vertical list which presents the view that invoked the menu and is useful to provide an overflow of actions related to specific content.

Toast

Android Toast can be used to display information for a short period of time. A toast contains a message to be displayed quickly and disappears after some time.

The android.widget.Toast class is the subclass of java.lang.Object class. You can also create custom toast as well for example toast displaying images.  Toast class is used to show notification for a particular interval of time. After some time it disappears. It doesn’t block the user interaction.

Constants of Toast class

There are only 2 constants of Toast class which are given below.

ConstantDescription
public static final int LENGTH_LONGdisplays view for the long duration of time.
public static final int LENGTH_SHORTdisplays view for the short duration of time.

Methods of Toast class

The widely used methods of Toast class are given below.

MethodDescription
public static Toast makeText(Context context, CharSequence text, int duration)makes the toast containing text and duration.
public void show()displays toast.
public void setMargin (float horizontalMargin, float verticalMargin)changes the horizontal and vertical margin difference.

Android Toast Example

Toast.makeText(getApplicationContext(),”Hello Javatpoint”,Toast.LENGTH_SHORT).show();  

Another code:

Toast toast=Toast.makeText(getApplicationContext(),”Hello Javatpoint”,Toast.LENGTH_SHORT);  

toast.setMargin(50,50);  

toast.show();  

Here, getApplicationContext() method returns the instance of Context.

Dialogs

A Dialog is small window that prompts the user to a decision or enter additional information Some times in your application, if you wanted to ask the user about taking a decision between yes or no in response of any particular action taken by the user, by remaining in the same activity and without changing the screen, you can use Alert Dialog.

In order to make an alert dialog, you need to make an object of AlertDialogBuilder which is an inner class of AlertDialog. Its syntax is given below

AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);

alertDialogBuilder.setPositiveButton(CharSequence text, 

   DialogInterface.OnClickListener listener)

alertDialogBuilder.setNegativeButton(CharSequence text, 

   DialogInterface.OnClickListener listener)

Sr.NoMethod type & description
1setIcon(Drawable icon)This method sets the icon of the alert dialog box.
2setCancelable(boolean cancel able)This method sets the property that the dialog can be cancelled or not
3setMessage(CharSequence message)This method sets the message to be displayed in the alert dialog
4setMultiChoiceItems(CharSequence[] items, boolean[] checkedItems, DialogInterface.OnMultiChoiceClickListener listener)This method sets a list of items to be displayed in the dialog as the content. The selected option will be notified by the listener
5setOnCancelListener(DialogInterface.OnCancelListener onCancelListener)This method Sets the callback that will be called if the dialog is cancelled.
6setTitle(CharSequence title)This method set the title to be appear in the dialog

After creating and setting the dialog builder , you will create an alert dialog by calling the create() method of the builder class. Its syntax is

AlertDialog alertDialog = alertDialogBuilder.create();

alertDialog.show();

Styles and Themes

A style is defined in an XML resource that is separate from the XML that specifies the layout. This XML file resides under the res/values/ directory of your project and will have <resources> as the root node which is mandatory for the style file. The name of the XML file is arbitrary, but it must use the .xml extension.

You can define multiple styles per file using <style> tag but each style will have its name that uniquely identifies the style. Android style attributes are set using <item> tag as shown below −

<?xml version=”1.0″ encoding=”utf-8″?>

<resources>

   <style name=”CustomFontStyle”>

      <item name=”android:layout_width”>fill_parent</item>

      <item name=”android:layout_height”>wrap_content</item>

      <item name=”android:capitalize”>characters</item>

      <item name=”android:typeface”>monospace</item>

      <item name=”android:textSize”>12pt</item>

      <item name=”android:textColor”>#00FF00</item>/> 

   </style>

</resources>

The value for the <item> can be a keyword string, a hex color, a reference to another resource type, or other value depending on the style property.

Android Themes

A theme is nothing but an Android style applied to an entire Activity or application, rather than an individual View. Thus, when a style is applied as a theme, every View in the Activity or application will apply each style property that it supports. 

For example, you can apply the same CustomFontStyle style as a theme for an Activity and then all text inside that Activity will have green monospace font. To set a theme for all the activities of your application, open the AndroidManifest.xml file and edit the <application> tag to include the android:theme attribute with the style name. 

For example −

<application android:theme=”@style/CustomFontStyle”>

But if you want a theme applied to just one Activity in your application, then add the android:theme attribute to the <activity> tag only. 

For example −

<activity android:theme=”@style/CustomFontStyle”>

There are number of default themes defined by Android which you can use directly or inherit them using parent attribute as follows −

<style name=”CustomTheme” parent=”android:Theme.Light”>

   …

</style>

Default Styles & Themes

The Android platform provides a large collection of styles and themes that you can use in your applications. You can find a reference of all available styles in the R.style class. To use the styles listed here, replace all underscores in the style name with a period. For example, you can apply the Theme_NoTitleBar theme with “@android:style/Theme.NoTitleBar”. 

Creating lists

First we need to drag and drop ListView component from palette to activity_main.xml file.

File: activity_main.xml

<?xml version=”1.0″ encoding=”utf-8″?>  

<android.support.constraint.ConstraintLayout xmlns:android=”http://schemas.android.com/apk/res/android”  

    xmlns:app=”http://schemas.android.com/apk/res-auto”  

    xmlns:tools=”http://schemas.android.com/tools”  

    android:layout_width=”match_parent”  

    android:layout_height=”match_parent”  

    tools:context=”listview.example.com.listview.MainActivity”>  

    <ListView  

        android:id=”@+id/listView”  

        android:layout_width=”match_parent”  

        android:layout_height=”fill_parent”  

         />  

</android.support.constraint.ConstraintLayout>

Create an additional mylist.xml file in the layout folder which contains view components displayed in listview.

File: mylist.xml

<?xml version=”1.0″ encoding=”utf-8″?>  

<TextView xmlns:android=”http://schemas.android.com/apk/res/android”  

    android:id=”@+id/textView”  

    android:layout_width=”wrap_content”  

    android:layout_height=”wrap_content”  

    android:text=”Medium Text”  

    android:textStyle=”bold”  

    android:textAppearance=”?android:attr/textAppearanceMedium”  

    android:layout_marginLeft=”10dp”  

    android:layout_marginTop=”5dp”  

    android:padding=”2dp”  

    android:textColor=”#4d4d4d”  

     />  

Now place the list of data in strings.xml file by creating string-array.

File:strings.xml

<resources>  

    <string name=”app_name”>ListView</string>  

    <string-array name=”array_technology”>  

        <item>Android</item>  

        <item>Java</item>  

        <item>Php</item>  

        <item>Hadoop</item>  

        <item>Sap</item>  

        <item>Python</item>  

        <item>Ajax</item>  

        <item>C++</item>  

        <item>Ruby</item>  

        <item>Rails</item>  

        <item>.Net</item>  

        <item>Perl</item>  

    </string-array>  

</resources>  

In java class we need to add an adapter to listview using setAdapter() method of listview.

File: MainActivity.java

package listview.example.com.listview;    

import android.support.v7.app.AppCompatActivity;  

import android.os.Bundle;  

import android.view.View;  

import android.widget.AdapterView;  

import android.widget.ArrayAdapter;  

import android.widget.ListView;  

import android.widget.TextView;  

import android.widget.Toast;  

public class MainActivity extends AppCompatActivity {  

    ListView listView;  

    TextView textView;  

    String[] listItem;  

    @Override  

    protected void onCreate(Bundle savedInstanceState) {  

        super.onCreate(savedInstanceState);  

        setContentView(R.layout.activity_main);  

        listView=(ListView)findViewById(R.id.listView);  

        textView=(TextView)findViewById(R.id.textView);  

        listItem = getResources().getStringArray(R.array.array_technology);  

        final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,  

                android.R.layout.simple_list_item_1, android.R.id.text1, listItem);  

        listView.setAdapter(adapter);  

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {  

            @Override  

            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {  

                String value=adapter.getItem(position);  

                Toast.makeText(getApplicationContext(),value,Toast.LENGTH_SHORT).show();  

            }  

        });  

    }  

}  

Output

Custom lists

After creating a simple ListView, android also provides facilities to customise our ListView.

As the simple ListView, custom ListView also uses Adapter classes which add the content from data source (such as string array, array, database etc). Adapter bridges data between an AdapterViews and other Views

Create an activity_main.xml file in the layout folder.

<?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:paddingBottom=”@dimen/activity_vertical_margin”  

    android:paddingLeft=”@dimen/activity_horizontal_margin”  

    android:paddingRight=”@dimen/activity_horizontal_margin”  

    android:paddingTop=”@dimen/activity_vertical_margin”  

    tools:context=”com.example.test.listviewwithimage.MainActivity”>  

    <ListView  

        android:id=”@+id/list”  

        android:layout_width=”match_parent”  

        android:layout_height=”wrap_content”  

        android:layout_marginBottom=”50dp”>  

    </ListView>  

</RelativeLayout>  

Create an additional mylist.xml file in the layout folder which contains view components displayed in listview.

File: mylist.xml

<?xml version=”1.0″ encoding=”utf-8″?>  

<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”  

    android:layout_width=”match_parent”  

    android:layout_height=”match_parent”  

    android:orientation=”horizontal” >  

    <ImageView  

        android:id=”@+id/icon”  

        android:layout_width=”60dp”  

        android:layout_height=”60dp”  

        android:padding=”5dp” />  

    <LinearLayout android:layout_width=”wrap_content”  

        android:layout_height=”wrap_content”  

        android:orientation=”vertical”>  

    <TextView  

        android:id=”@+id/title”  

        android:layout_width=”wrap_content”  

        android:layout_height=”wrap_content”  

        android:text=”Medium Text”  

        android:textStyle=”bold”  

        android:textAppearance=”?android:attr/textAppearanceMedium”  

        android:layout_marginLeft=”10dp”  

        android:layout_marginTop=”5dp”  

        android:padding=”2dp”  

        android:textColor=”#4d4d4d” />  

    <TextView  

        android:id=”@+id/subtitle”  

        android:layout_width=”wrap_content”  

        android:layout_height=”wrap_content”  

        android:text=”TextView”   

        android:layout_marginLeft=”10dp”/>  

    </LinearLayout>  

</LinearLayout>  

Place the all required images in drawable folder.

Activity class

File: MainActivity.java

package com.example.test.listviewwithimage;    

import android.support.v7.app.AppCompatActivity;  

import android.os.Bundle;  

import android.view.View;  

import android.widget.AdapterView;  

import android.widget.ListView;  

import android.widget.Toast;  

public class MainActivity extends AppCompatActivity {  

    ListView list;    

    String[] maintitle ={  

            “Title 1″,”Title 2”,  

            “Title 3″,”Title 4”,  

            “Title 5”,  

    };  

    String[] subtitle ={  

            “Sub Title 1″,”Sub Title 2”,  

            “Sub Title 3″,”Sub Title 4”,  

            “Sub Title 5”,  

    };    

    Integer[] imgid={  

            R.drawable.download_1,R.drawable.download_2,  

            R.drawable.download_3,R.drawable.download_4,  

            R.drawable.download_5,  

    };  

    @Override  

    protected void onCreate(Bundle savedInstanceState) {  

        super.onCreate(savedInstanceState);  

        setContentView(R.layout.activity_main);  

        MyListAdapter adapter=new MyListAdapter(this, maintitle, subtitle,imgid);  

        list=(ListView)findViewById(R.id.list);  

        list.setAdapter(adapter);   

        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {  

            @Override  

            public void onItemClick(AdapterView<?> parent, View view,int position, long id) {  

                if(position == 0) {  

                    Toast.makeText(getApplicationContext(),”Place Your First Option Code”,Toast.LENGTH_SHORT).show();  

                }else if(position == 1) {  

                    Toast.makeText(getApplicationContext(),”Place Your Second Option Code”,Toast.LENGTH_SHORT).show();  

                }else if(position == 2) {  

                    Toast.makeText(getApplicationContext(),”Place Your Third Option Code”,Toast.LENGTH_SHORT).show();  

                }else if(position == 3) {  

                    Toast.makeText(getApplicationContext(),”Place Your Forth Option Code”,Toast.LENGTH_SHORT).show();  

                }else if(position == 4) {  

                    Toast.makeText(getApplicationContext(),”Place Your Fifth Option Code”,Toast.LENGTH_SHORT).show();  

                }    

            }  

        });  

    }  

}  

Output