0% found this document useful (0 votes)
14 views

Unit 3

Views and ViewGroups are the basic building blocks of Android user interfaces. Views are responsible for drawing and handling interactions, and ViewGroups arrange Views visually. Common layouts like LinearLayout and RelativeLayout extend ViewGroup to define the structure of an UI. Layouts can be created in XML and loaded in code. Common UI controls include buttons, text fields, checkboxes which are subclasses of View. Attributes like width, height, gravity control View positioning and sizing.

Uploaded by

Chess Blogs
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Unit 3

Views and ViewGroups are the basic building blocks of Android user interfaces. Views are responsible for drawing and handling interactions, and ViewGroups arrange Views visually. Common layouts like LinearLayout and RelativeLayout extend ViewGroup to define the structure of an UI. Layouts can be created in XML and loaded in code. Common UI controls include buttons, text fields, checkboxes which are subclasses of View. Attributes like width, height, gravity control View positioning and sizing.

Uploaded by

Chess Blogs
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 48

Android - UI Layouts

The basic building block for user interface is a View object which is created from the View
class and occupies a rectangular area on the screen and is responsible for drawing and event
handling. View is the base class for widgets, which are used to create interactive UI components
like buttons, text fields, etc.
The ViewGroup is a subclass of View and provides invisible container that hold other Views or
other ViewGroups and define their layout properties.
At third level we have different layouts which are subclasses of ViewGroup class and a typical
layout defines the visual structure for an Android user interface and can be created either at run
time using View/ViewGroup objects or you can declare your layout using simple XML
file main_layout.xml which is located in the res/layout folder of your project.

Layout params
This tutorial is more about creating your GUI based on layouts defined in XML file. A layout
may contain any type of widgets such as buttons, labels, textboxes, and so on.
Following is a simple example of XML file having LinearLayout −
<?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="wrap_content"
android:layout_height="wrap_content"
android:text="This is a TextView" />

<Button android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is a Button" />

<!-- More GUI components go here -->

</LinearLayout>
Once your layout has created, you can load the layout resource from your application code, in
your Activity.onCreate() callback implementation as shown below −
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

Android Layout Types


There are number of Layouts provided by Android which you will use in almost all the Android
applications to provide different view, look and feel.

Sr.No Layout & Description

1 Linear Layout

LinearLayout is a view group that aligns all children in a single direction, vertically or horizontally.

2 Relative Layout

RelativeLayout is a view group that displays child views in relative positions.

3 Table Layout

TableLayout is a view that groups views into rows and columns.

4 Absolute Layout

AbsoluteLayout enables you to specify the exact location of its children.

5 Frame Layout

The FrameLayout is a placeholder on screen that you can use to display a single view.
6 List View

ListView is a view group that displays a list of scrollable items.

7 Grid View

GridView is a ViewGroup that displays items in a two-dimensional, scrollable grid.

Layout Attributes
Each layout has a set of attributes which define the visual properties of that layout. There are
few common attributes among all the layouts and their are other attributes which are specific to
that layout. Following are common attributes and will be applied to all the layouts:

Sr.No Attribute & Description

1
android:id
This is the ID which uniquely identifies the view.

2
android:layout_width
This is the width of the layout.

3
android:layout_height
This is the height of the layout

4
android:layout_marginTop
This is the extra space on the top side of the layout.

5
android:layout_marginBottom
This is the extra space on the bottom side of the layout.

6
android:layout_marginLeft
This is the extra space on the left side of the layout.

7
android:layout_marginRight
This is the extra space on the right side of the layout.

8
android:layout_gravity
This specifies how child Views are positioned.

9
android:layout_weight
This specifies how much of the extra space in the layout should be allocated to the View.

10
android:layout_x
This specifies the x-coordinate of the layout.

11
android:layout_y
This specifies the y-coordinate of the layout.

12
android:layout_width
This is the width of the layout.

13
android:paddingLeft
This is the left padding filled for the layout.

14
android:paddingRight
This is the right padding filled for the layout.

15
android:paddingTop
This is the top padding filled for the layout.

16
android:paddingBottom
This is the bottom padding filled for the layout.
Here width and height are the dimension of the layout/view which can be specified in terms of
dp (Density-independent Pixels), sp ( Scale-independent Pixels), pt ( Points which is 1/72 of an
inch), px( Pixels), mm ( Millimeters) and finally in (inches).
You can specify width and height with exact measurements but more often, you will use one of
these constants to set the width or height −
 android:layout_width=wrap_content tells your view to size itself to the dimensions
required by its content.
 android:layout_width=fill_parent tells your view to become as big as its parent view.

Gravity attribute plays important role in positioning the view object and it can take one or more
(separated by '|') of the following constant values.

Constant Value Description

Top 0x30 Push object to the top of its container, not changing its size.

Bottom 0x50 Push object to the bottom of its container, not changing its size.

Left 0x03 Push object to the left of its container, not changing its size.

Right 0x05 Push object to the right of its container, not changing its size.

center_vertical 0x10 Place object in the vertical center of its container, not changing its size.

fill_vertical 0x70 Grow the vertical size of the object if needed so it completely fills its container.

center_horizonta 0x01 Place object in the horizontal center of its container, not changing its size.
l

fill_horizontal 0x07 Grow the horizontal size of the object if needed so it completely fills its container.

Center 0x11 Place the object in the center of its container in both the vertical and horizontal
axis, not changing its size.

Fill 0x77 Grow the horizontal and vertical size of the object if needed so it completely fills
its container.

clip_vertical 0x80 Additional option that can be set to have the top and/or bottom edges of the child
clipped to its container's bounds. The clip will be based on the vertical gravity: a
top gravity will clip the bottom edge, a bottom gravity will clip the top edge, and
neither will clip both edges.

clip_horizontal 0x08 Additional option that can be set to have the left and/or right edges of the child
clipped to its container's bounds. The clip will be based on the horizontal gravity: a
left gravity will clip the right edge, a right gravity will clip the left edge, and
neither will clip both edges.

Start 0x00800003 Push object to the beginning of its container, not changing its size.

End 0x00800005 Push object to the end of its container, not changing its size.

View Identification
A view object may have a unique ID assigned to it which will identify the View uniquely within
the tree. The syntax for an ID, inside an XML tag is −
android:id="@+id/my_button"
Following is a brief description of @ and + signs −
 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 our resources. To create an instance of the view object and capture it from the
layout, use the following −
Button myButton = (Button) findViewById(R.id.my_button);

Android - UI Controls
Input controls are the interactive components in your app's user interface. Android
provides a wide variety of controls you can use in your UI, such as buttons, text fields,
seek bars, check box, zoom buttons, toggle buttons, and many more.
UI Elements
A View is an object that draws something on the screen that the user can interact with
and a ViewGroup is an object that holds other View (and ViewGroup) objects in order
to define the layout of the user interface.
You define your layout in an XML file which offers a human-readable structure for the
layout, similar to HTML. For example, a simple vertical layout with a text view and a
button looks like this −
<?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="wrap_content"
android:layout_height="wrap_content"
android:text="I am a TextView" />

<Button android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I am a Button" />
</LinearLayout>

Android UI Controls
There are number of UI controls provided by Android that allow you to build the
graphical user interface for your app.

Sr.No UI Control & Description


.
1 TextView

This control is used to display text to the user.

2 EditText

EditText is a predefined subclass of TextView that includes rich editing capabilities.

3 AutoCompleteTextView

The AutoCompleteTextView is a view that is similar to EditText, except that it shows a list
of completion suggestions automatically while the user is typing.

4 Button

A push-button that can be pressed, or clicked, by the user to perform an action.

5 ImageButton

An ImageButton is an AbsoluteLayout which enables you to specify the exact location of


its children. This shows a button with an image (instead of text) that can be pressed or
clicked by the user.

6 CheckBox

An on/off switch that can be toggled by the user. You should use check box when
presenting users with a group of selectable options that are not mutually exclusive.

7 ToggleButton

An on/off button with a light indicator.

8 RadioButton

The RadioButton has two states: either checked or unchecked.

9 RadioGroup

A RadioGroup is used to group together one or more RadioButtons.

10 ProgressBar

The ProgressBar view provides visual feedback about some ongoing tasks, such as
when you are performing a task in the background.
11 Spinner

A drop-down list that allows users to select one value from a set.

12 TimePicker

The TimePicker view enables users to select a time of the day, in either 24-hour mode or
AM/PM mode.

13 DatePicker

The DatePicker view enables users to select a date of the day.

Create UI Controls
Input controls are the interactive components in your app's user interface. Android
provides a wide variety of controls you can use in your UI, such as buttons, text fields,
seek bars, check box, zoom buttons, toggle buttons, and many more.
As explained in previous chapter, a view object may have a unique ID assigned to it
which will identify the View uniquely within the tree. The syntax for an ID, inside an
XML tag is −
android:id="@+id/text_id"

To create a UI Control/View/Widget you will have to define a view/widget in the layout


file and assign it a unique ID as follows −
<?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_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I am a TextView" />
</LinearLayout>

Then finally create an instance of the Control object and capture it from the layout, use
the following −
TextView myText = (TextView) findViewById(R.id.text_id);
Android Widgets
There are given a lot of android widgets with simplified examples such as Button,
EditText, AutoCompleteTextView, ToggleButton, DatePicker, TimePicker, ProgressBar etc.

Android widgets are easy to learn. The widely used android widgets with examples are
given below:

Android Button

Let's learn how to perform event handling on button click.

Android Toast

Displays information for the short duration of time.

Custom Toast

We are able to customize the toast, such as we can display image on the toast

ToggleButton

It has two states ON/OFF.

CheckBox

Let's see the application of simple food ordering.

AlertDialog

AlertDialog displays a alert dialog containing the message with OK and Cancel buttons.

Spinner

Spinner displays the multiple options, but only one can be selected at a time.

AutoCompleteTextView

Let's see the simple example of AutoCompleteTextView.

RatingBar
RatingBar displays the rating bar.

DatePicker

Datepicker displays the datepicker dialog that can be used to pick the date.

TimePicker

TimePicker displays the timepicker dialog that can be used to pick the time.

ProgressBar

ProgressBar displays progress task.

Android Button Example

Android Button represents a push-button. The android.widget.Button is 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.
Android Button Example with Listener
Here, we are going to create two textfields and one button for sum of two numbers. If
user clicks button, sum of two input values is displayed on the Toast.

We can perform action on button using different types such as calling listener on button
or adding onClick property of button in activity's xml file.

1. button.setOnClickListener(new View.OnClickListener() {  
2.             @Override  
3.             public void onClick(View view) {  
4.                //code  
5.             }  
6. });  
1. <Button  
2.         android:onClick="methodName"  
3. />  
Drag the component or write the code for UI in
activity_main.xml
First of all, drag 2 textfields from the Text Fields palette and one button from the Form
Widgets palette as shown in the following figure.
The generated code for the ui components will be like this:

File: activity_main.xml

1. <?xml version="1.0" encoding="utf-8"?>  
2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
3.     xmlns:app="http://schemas.android.com/apk/res-auto"  
4.     xmlns:tools="http://schemas.android.com/tools"  
5.     android:layout_width="match_parent"  
6.     android:layout_height="match_parent"  
7.     tools:context="example.javatpoint.com.sumoftwonumber.MainActivity">  
8.   
9.     <EditText  
10.         android:id="@+id/editText1"  
11.         android:layout_width="wrap_content"  
12.         android:layout_height="wrap_content"  
13.         android:layout_alignParentTop="true"  
14.         android:layout_centerHorizontal="true"  
15.         android:layout_marginTop="61dp"  
16.         android:ems="10"  
17.         android:inputType="number"  
18.         tools:layout_editor_absoluteX="84dp"  
19.         tools:layout_editor_absoluteY="53dp" />  
20.   
21.     <EditText  
22.         android:id="@+id/editText2"  
23.         android:layout_width="wrap_content"  
24.         android:layout_height="wrap_content"  
25.         android:layout_below="@+id/editText1"  
26.         android:layout_centerHorizontal="true"  
27.         android:layout_marginTop="32dp"  
28.         android:ems="10"  
29.         android:inputType="number"  
30.         tools:layout_editor_absoluteX="84dp"  
31.         tools:layout_editor_absoluteY="127dp" />  
32.   
33.     <Button  
34.         android:id="@+id/button"  
35.         android:layout_width="wrap_content"  
36.         android:layout_height="wrap_content"  
37.         android:layout_below="@+id/editText2"  
38.         android:layout_centerHorizontal="true"  
39.         android:layout_marginTop="109dp"  
40.         android:text="ADD"  
41.         tools:layout_editor_absoluteX="148dp"  
42.         tools:layout_editor_absoluteY="266dp" />  
43. </RelativeLayout>  
Activity class
Now write the code to display the sum of two numbers.

File: MainActivity.java

1. package example.javatpoint.com.sumoftwonumber;  
2.   
3. import android.support.v7.app.AppCompatActivity;  
4. import android.os.Bundle;  
5. import android.view.View;  
6. import android.widget.Button;  
7. import android.widget.EditText;  
8. import android.widget.Toast;  
9.   
10. public class MainActivity extends AppCompatActivity {  
11.     private EditText edittext1, edittext2;  
12.     private Button buttonSum;  
13.   
14.     @Override  
15.     protected void onCreate(Bundle savedInstanceState) {  
16.         super.onCreate(savedInstanceState);  
17.         setContentView(R.layout.activity_main);  
18.         addListenerOnButton();  
19.     }  
20.   
21.     public void addListenerOnButton() {  
22.         edittext1 = (EditText) findViewById(R.id.editText1);  
23.         edittext2 = (EditText) findViewById(R.id.editText2);  
24.         buttonSum = (Button) findViewById(R.id.button);  
25.   
26.         buttonSum.setOnClickListener(new View.OnClickListener() {  
27.             @Override  
28.             public void onClick(View view) {  
29.                 String value1=edittext1.getText().toString();  
30.                 String value2=edittext2.getText().toString();  
31.                 int a=Integer.parseInt(value1);  
32.                 int b=Integer.parseInt(value2);  
33.                 int sum=a+b;  
34.                 Toast.makeText(getApplicationContext(),String.valueOf(sum), Toast.LEN
GTH_LONG).show();  
35.             }  
36.         });  
37.     }  
38. }  

Android Toast Example

Andorid Toast can be used to display information for the short period of time. A toast
contains message to be displayed quickly and disappears after sometime.

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 image. You can
visit next page to see the code for custom toast.

Toast class
Toast class is used to show notification for a particular interval of time. After sometime 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.

Constant Description
public static final int LENGTH_LONG displays view for the long duration of time.

public static final int LENGTH_SHORT displays view for the short duration of time.

Methods of Toast class

The widely used methods of Toast class are given below.

Method Description

public static Toast makeText(Context context, CharSequence text, int makes the toast containing text a
duration)

public void show() displays toast.

public void setMargin (float horizontalMargin, float verticalMargin) changes the horizontal and
difference.

Android Toast Example


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

Another code:

1. Toast toast=Toast.makeText(getApplicationContext(),"Hello Javatpoint",Toast.LEN
GTH_SHORT);  
2. toast.setMargin(50,50);  
3. toast.show();  

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

Full code of activity class displaying Toast


Let's see the code to display the toast.

File: MainActivity.java

1. package example.javatpoint.com.toast;  
2.   
3. import android.support.v7.app.AppCompatActivity;  
4. import android.os.Bundle;  
5. import android.widget.Toast;  
6.   
7. public class MainActivity extends AppCompatActivity {  
8.   
9.     @Override  
10.     protected void onCreate(Bundle savedInstanceState) {  
11.         super.onCreate(savedInstanceState);  
12.         setContentView(R.layout.activity_main);  
13.   
14.         //Displaying Toast with Hello Javatpoint message  
15.         Toast.makeText(getApplicationContext(),"Hello Javatpoint",Toast.LENGTH_S
HORT).show();  
16.     }  
17. }  
Android ToggleButton Example

Android Toggle Button can be used to display checked/unchecked (On/Off) state on


the button.

It is beneficial if user have to change the setting between two states. It can be used to
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.

Android ToggleButton class


ToggleButton class provides the facility of creating the toggle button.

XML Attributes of ToggleButton class


The 3 XML attributes of ToggleButton class.
XML Attribute Description

android:disabledAlpha The alpha to apply to the indicator when disabled.

android:textOff The text for the button when it is not checked.

android:textOn The text for the button when it is checked.

Methods of ToggleButton class


The widely used methods of ToggleButton class are given below.

Method Description

CharSequence getTextOff() Returns the text when button is not in the checked state.

CharSequence getTextOn() Returns the text for when button is in the checked state.

void setChecked(boolean checked) Changes the checked state of this button.

Android ToggleButton Example


activity_main.xml

Drag two toggle button and one button for the layout. Now the activity_main.xml file
will look like this:

File: activity_main.xml

1. <?xml version="1.0" encoding="utf-8"?>  
2. <android.support.constraint.ConstraintLayout xmlns:android="http://
schemas.android.com/apk/res/android"  
3.     xmlns:app="http://schemas.android.com/apk/res-auto"  
4.     xmlns:tools="http://schemas.android.com/tools"  
5.     android:layout_width="match_parent"  
6.     android:layout_height="match_parent"  
7.     tools:context="example.javatpoint.com.togglebutton.MainActivity">  
8.   
9.     <ToggleButton  
10.         android:id="@+id/toggleButton"  
11.         android:layout_width="wrap_content"  
12.         android:layout_height="wrap_content"  
13.         android:layout_marginLeft="8dp"  
14.         android:layout_marginTop="80dp"  
15.         android:text="ToggleButton"  
16.         android:textOff="Off"  
17.         android:textOn="On"  
18.         app:layout_constraintEnd_toStartOf="@+id/toggleButton2"  
19.         app:layout_constraintStart_toStartOf="parent"  
20.         app:layout_constraintTop_toTopOf="parent" />  
21.   
22.     <ToggleButton  
23.         android:id="@+id/toggleButton2"  
24.         android:layout_width="wrap_content"  
25.         android:layout_height="wrap_content"  
26.         android:layout_marginRight="60dp"  
27.         android:layout_marginTop="80dp"  
28.         android:text="ToggleButton"  
29.         android:textOff="Off"  
30.         android:textOn="On"  
31.         app:layout_constraintEnd_toEndOf="parent"  
32.         app:layout_constraintTop_toTopOf="parent" />  
33.   
34.     <Button  
35.         android:id="@+id/button"  
36.         android:layout_width="wrap_content"  
37.         android:layout_height="wrap_content"  
38.         android:layout_marginBottom="144dp"  
39.         android:layout_marginLeft="148dp"  
40.         android:text="Submit"  
41.         app:layout_constraintBottom_toBottomOf="parent"  
42.         app:layout_constraintStart_toStartOf="parent" />  
43. </android.support.constraint.ConstraintLayout>  

Activity class

Let's write the code to check which toggle button is ON/OFF.

File: MainActivity.java

1. package example.javatpoint.com.togglebutton;  
2.   
3. import android.support.v7.app.AppCompatActivity;  
4. import android.os.Bundle;  
5. import android.view.View;  
6. import android.widget.Button;  
7. import android.widget.Toast;  
8. import android.widget.ToggleButton;  
9.   
10. public class MainActivity extends AppCompatActivity {  
11.     private ToggleButton toggleButton1, toggleButton2;  
12.     private Button buttonSubmit;  
13.     @Override  
14.     protected void onCreate(Bundle savedInstanceState) {  
15.         super.onCreate(savedInstanceState);  
16.         setContentView(R.layout.activity_main);  
17.   
18.         addListenerOnButtonClick();  
19.     }  
20.   
21.     public void addListenerOnButtonClick(){  
22.         //Getting the ToggleButton and Button instance from the layout xml file  
23.         toggleButton1=(ToggleButton)findViewById(R.id.toggleButton);  
24.         toggleButton2=(ToggleButton)findViewById(R.id.toggleButton2);  
25.         buttonSubmit=(Button)findViewById(R.id.button);  
26.   
27.         //Performing action on button click  
28.         buttonSubmit.setOnClickListener(new View.OnClickListener(){  
29.   
30.             @Override  
31.             public void onClick(View view) {  
32.                 StringBuilder result = new StringBuilder();  
33.                 result.append("ToggleButton1 : ").append(toggleButton1.getText());  
34.                 result.append("\nToggleButton2 : ").append(toggleButton2.getText());  
35.                 //Displaying the message in toast  
36.                 Toast.makeText(getApplicationContext(), result.toString(),Toast.LENGTH_LONG)
.show();  
37.             }  
38.   
39.         });  
40.   
41.     }  
42. }  
Android CheckBox Example

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.

Android CheckBox 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:

Method Description
public boolean isChecked() Returns true if it is checked otherwise false.

public void setChecked(boolean status) Changes the state of the CheckBox.

Android CheckBox Example


activity_main.xml

Drag the three checkboxes and one button for the layout. Now the activity_main.xml file
will look like this:

File: activity_main.xml

1. <?xml version="1.0" encoding="utf-8"?>  
2. <android.support.constraint.ConstraintLayout xmlns:android="http://
schemas.android.com/apk/res/android"  
3.     xmlns:app="http://schemas.android.com/apk/res-auto"  
4.     xmlns:tools="http://schemas.android.com/tools"  
5.     android:layout_width="match_parent"  
6.     android:layout_height="match_parent"  
7.     tools:context="example.javatpoint.com.checkbox.MainActivity">  
8.   
9.   
10.     <CheckBox  
11.         android:id="@+id/checkBox"  
12.         android:layout_width="wrap_content"  
13.         android:layout_height="wrap_content"  
14.         android:layout_marginLeft="144dp"  
15.         android:layout_marginTop="68dp"  
16.         android:text="Pizza"  
17.         app:layout_constraintStart_toStartOf="parent"  
18.         app:layout_constraintTop_toTopOf="parent" />  
19.   
20.     <CheckBox  
21.         android:id="@+id/checkBox2"  
22.         android:layout_width="wrap_content"  
23.         android:layout_height="wrap_content"  
24.         android:layout_marginLeft="144dp"  
25.         android:layout_marginTop="28dp"  
26.         android:text="Coffee"  
27.         app:layout_constraintStart_toStartOf="parent"  
28.         app:layout_constraintTop_toBottomOf="@+id/checkBox" />  
29.   
30.     <CheckBox  
31.         android:id="@+id/checkBox3"  
32.         android:layout_width="wrap_content"  
33.         android:layout_height="wrap_content"  
34.         android:layout_marginLeft="144dp"  
35.         android:layout_marginTop="28dp"  
36.         android:text="Burger"  
37.         app:layout_constraintStart_toStartOf="parent"  
38.         app:layout_constraintTop_toBottomOf="@+id/checkBox2" />  
39.   
40.     <Button  
41.         android:id="@+id/button"  
42.         android:layout_width="wrap_content"  
43.         android:layout_height="wrap_content"  
44.         android:layout_marginLeft="144dp"  
45.         android:layout_marginTop="184dp"  
46.         android:text="Order"  
47.         app:layout_constraintStart_toStartOf="parent"  
48.         app:layout_constraintTop_toBottomOf="@+id/checkBox3" />  
49.   
50. </android.support.constraint.ConstraintLayout>  

Activity class

Let's write the code to check which toggle button is ON/OFF.

File: MainActivity.java
1. package example.javatpoint.com.checkbox;  
2.   
3. import android.support.v7.app.AppCompatActivity;  
4. import android.os.Bundle;  
5. import android.view.View;  
6. import android.widget.Button;  
7. import android.widget.CheckBox;  
8. import android.widget.Toast;  
9.   
10. public class MainActivity extends AppCompatActivity {  
11.     CheckBox pizza,coffe,burger;  
12.     Button buttonOrder;  
13.     @Override  
14.     protected void onCreate(Bundle savedInstanceState) {  
15.         super.onCreate(savedInstanceState);  
16.         setContentView(R.layout.activity_main);  
17.         addListenerOnButtonClick();  
18.     }  
19.     public void addListenerOnButtonClick(){  
20.         //Getting instance of CheckBoxes and Button from the activty_main.xml file  
21.         pizza=(CheckBox)findViewById(R.id.checkBox);  
22.         coffe=(CheckBox)findViewById(R.id.checkBox2);  
23.         burger=(CheckBox)findViewById(R.id.checkBox3);  
24.         buttonOrder=(Button)findViewById(R.id.button);  
25.   
26.         //Applying the Listener on the Button click  
27.         buttonOrder.setOnClickListener(new View.OnClickListener(){  
28.   
29.             @Override  
30.             public void onClick(View view) {  
31.                 int totalamount=0;  
32.                 StringBuilder result=new StringBuilder();  
33.                 result.append("Selected Items:");  
34.                 if(pizza.isChecked()){  
35.                     result.append("\nPizza 100Rs");  
36.                     totalamount+=100;  
37.                 }  
38.                 if(coffe.isChecked()){  
39.                     result.append("\nCoffe 50Rs");  
40.                     totalamount+=50;  
41.                 }  
42.                 if(burger.isChecked()){  
43.                     result.append("\nBurger 120Rs");  
44.                     totalamount+=120;  
45.                 }  
46.                 result.append("\nTotal: "+totalamount+"Rs");  
47.                 //Displaying the message on the toast  
48.                 Toast.makeText(getApplicationContext(), result.toString(), Toast.LENGTH_LONG
).show();  
49.             }  
50.   
51.         });  
52.     }  
53. }  

Android Custom CheckBox


Android provides facility to customize the UI of view elements rather than default.

You are able to create custom CheckBox in android. So, you can add some different
images of checkbox on the layout.

Example of Custom CheckBox


In this example, we create both default as well as custom checkbox. Add the following
code in activity_main.xml file.

activity_main.xml
File: activity_main.xml
1. <?xml version="1.0" encoding="utf-8"?>  
2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
3.     xmlns:app="http://schemas.android.com/apk/res-auto"  
4.     xmlns:tools="http://schemas.android.com/tools"  
5.     android:layout_width="match_parent"  
6.     android:layout_height="match_parent"  
7.     tools:context="example.javatpoint.com.customcheckbox.MainActivity">  
8.   
9.   
10.     <TextView  
11.         android:id="@+id/textView1"  
12.         android:layout_width="fill_parent"  
13.         android:layout_height="wrap_content"  
14.         android:gravity="center_horizontal"  
15.         android:textSize="25dp"  
16.         android:text="Default Check Box"  
17.         android:layout_alignParentTop="true"  
18.         android:layout_alignParentLeft="true"  
19.         android:layout_alignParentStart="true" />  
20.   
21.     <CheckBox  
22.         android:layout_width="wrap_content"  
23.         android:layout_height="wrap_content"  
24.         android:text="New CheckBox"  
25.         android:id="@+id/checkBox"  
26.         android:layout_below="@+id/textView1"  
27.         android:layout_centerHorizontal="true"  
28.         android:layout_marginTop="46dp" />  
29.   
30.     <CheckBox  
31.         android:layout_width="wrap_content"  
32.         android:layout_height="wrap_content"  
33.         android:text="New CheckBox"  
34.         android:id="@+id/checkBox2"  
35.         android:layout_below="@+id/checkBox"  
36.         android:layout_alignLeft="@+id/checkBox"  
37.         android:layout_alignStart="@+id/checkBox" />  
38.   
39.     <View  
40.         android:layout_width="fill_parent"  
41.         android:layout_height="1dp"  
42.         android:layout_marginTop="200dp"  
43.         android:background="#B8B894"  
44.         android:id="@+id/viewStub" />  
45.   
46.     <CheckBox  
47.         android:layout_width="wrap_content"  
48.         android:layout_height="wrap_content"  
49.         android:text="CheckBox 1"  
50.         android:id="@+id/checkBox3"  
51.         android:button="@drawable/customcheckbox"  
52.         android:layout_below="@+id/viewStub"  
53.         android:layout_centerHorizontal="true"  
54.         android:layout_marginTop="58dp" />  
55.   
56.     <CheckBox  
57.         android:layout_width="wrap_content"  
58.         android:layout_height="wrap_content"  
59.         android:text="CheckBox 2"  
60.         android:id="@+id/checkBox4"  
61.         android:button="@drawable/customcheckbox"  
62.         android:layout_below="@+id/checkBox3"  
63.         android:layout_alignLeft="@+id/checkBox3"  
64.         android:layout_alignStart="@+id/checkBox3" />  
65.   
66.     <TextView  
67.         android:layout_width="wrap_content"  
68.         android:layout_height="wrap_content"  
69.         android:textAppearance="?android:attr/textAppearanceSmall"  
70.         android:textSize="25dp"  
71.         android:text="Custom Check Box"  
72.         android:id="@+id/textView"  
73.         android:layout_alignTop="@+id/viewStub"  
74.         android:layout_centerHorizontal="true" />  
75.   
76.     <Button  
77.         android:layout_width="wrap_content"  
78.         android:layout_height="wrap_content"  
79.         android:text="Show Checked"  
80.         android:id="@+id/button"  
81.         android:layout_alignParentBottom="true"  
82.         android:layout_centerHorizontal="true" />  
83.   
84. </RelativeLayout>  

Now implement a selector in another file (checkbox.xml) under drawable folder which
customizes the checkbox.

checkbox.xml
File: checkbox.xml

1. <?xml version="1.0" encoding="utf-8"?>  
2. <selector xmlns:android="http://schemas.android.com/apk/res/android">  
3.     <item android:state_checked="true" android:drawable="@drawable/checked" 
/>  
4.     <item android:state_checked="false" android:drawable="@drawable/unchecked"/>  
5. </selector>  
Activity class
File: MainActivity.java

1. package example.javatpoint.com.customcheckbox;  
2.   
3. import android.support.v7.app.AppCompatActivity;  
4. import android.os.Bundle;  
5. import android.view.View;  
6. import android.widget.Button;  
7. import android.widget.CheckBox;  
8. import android.widget.Toast;  
9.   
10. public class MainActivity extends AppCompatActivity {  
11.     CheckBox cb1,cb2;  
12.     Button button;  
13.     @Override  
14.     protected void onCreate(Bundle savedInstanceState) {  
15.         super.onCreate(savedInstanceState);  
16.         setContentView(R.layout.activity_main);  
17.         cb1=(CheckBox)findViewById(R.id.checkBox3);  
18.         cb2=(CheckBox)findViewById(R.id.checkBox4);  
19.         button=(Button)findViewById(R.id.button);  
20.   
21.         button.setOnClickListener(new View.OnClickListener() {  
22.             @Override  
23.             public void onClick(View v) {  
24.                 StringBuilder sb=new StringBuilder("");  
25.   
26.                 if(cb1.isChecked()){  
27.                     String s1=cb1.getText().toString();  
28.                     sb.append(s1);  
29.                 }  
30.   
31.                 if(cb2.isChecked()){  
32.                     String s2=cb2.getText().toString();  
33.                     sb.append("\n"+s2);  
34.   
35.                 }  
36.                 if(sb!=null && !sb.toString().equals("")){  
37.                     Toast.makeText(getApplicationContext(), sb, Toast.LENGTH_LONG).sh
ow();  
38.   
39.                 }  
40.                 else{  
41.                     Toast.makeText(getApplicationContext(),"Nothing Selected", Toast.LE
NGTH_LONG).show();  
42.                 }  
43.   
44.             }  
45.   
46.         });  
47.     }  
48. }  

Android RadioButton
RadioButton is a two states button which is either checked or unchecked. If a single
radio button is unchecked, we can click it to make checked radio button. Once a radio
button is checked, it cannot be marked as unchecked by 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.

Example of Radio Button


In this example, we are going to implement single radio button separately as well as
radio button in RadioGroup.

activity_main.xml
File: activity_main.xml

1. <?xml version="1.0" encoding="utf-8"?>  
2. <LinearLayout  
3.     xmlns:android="http://schemas.android.com/apk/res/android"  
4.     xmlns:tools="http://schemas.android.com/tools"  
5.     android:layout_width="match_parent"  
6.     android:layout_height="match_parent"  
7.     android:orientation="vertical"  
8.     tools:context="example.javatpoint.com.radiobutton.MainActivity">  
9.   
10.     <TextView  
11.         android:id="@+id/textView1"  
12.         android:layout_width="fill_parent"  
13.         android:layout_height="wrap_content"  
14.         android:layout_marginTop="30dp"  
15.         android:gravity="center_horizontal"  
16.         android:textSize="22dp"  
17.         android:text="Single Radio Buttons" />  
18.   
19.   
20.   
21.     <!--   Default RadioButtons  -->  
22.   
23.     <RadioButton  
24.         android:id="@+id/radioButton1"  
25.         android:layout_width="fill_parent"  
26.         android:layout_height="wrap_content"  
27.         android:layout_gravity="center_horizontal"  
28.         android:text="Radio Button 1"  
29.         android:layout_marginTop="20dp"  
30.   
31.         android:textSize="20dp" />  
32.     <RadioButton  
33.         android:id="@+id/radioButton2"  
34.         android:layout_width="fill_parent"  
35.         android:layout_height="wrap_content"  
36.         android:text="Radio Button 2"  
37.         android:layout_marginTop="10dp"  
38.   
39.         android:textSize="20dp" />  
40.   
41.   
42.     <View  
43.         android:layout_width="fill_parent"  
44.         android:layout_height="1dp"  
45.         android:layout_marginTop="20dp"  
46.         android:background="#B8B894" />  
47.   
48.     <TextView  
49.         android:id="@+id/textView2"  
50.         android:layout_width="fill_parent"  
51.         android:layout_height="wrap_content"  
52.         android:layout_marginTop="30dp"  
53.         android:gravity="center_horizontal"  
54.         android:textSize="22dp"  
55.         android:text="Radio button inside RadioGroup" />  
56.   
57.   
58.     <!--   Customized RadioButtons  -->  
59.   
60.   
61.     <RadioGroup  
62.         android:layout_width="wrap_content"  
63.         android:layout_height="wrap_content"  
64.         android:id="@+id/radioGroup">  
65.   
66.         <RadioButton  
67.             android:id="@+id/radioMale"  
68.             android:layout_width="fill_parent"  
69.             android:layout_height="wrap_content"  
70.             android:text="  Male"  
71.             android:layout_marginTop="10dp"  
72.             android:checked="false"  
73.             android:textSize="20dp" />  
74.   
75.         <RadioButton  
76.             android:id="@+id/radioFemale"  
77.             android:layout_width="fill_parent"  
78.             android:layout_height="wrap_content"  
79.             android:text="   Female"  
80.             android:layout_marginTop="20dp"  
81.             android:checked="false"  
82.   
83.             android:textSize="20dp" />  
84.     </RadioGroup>  
85.   
86.     <Button  
87.         android:layout_width="wrap_content"  
88.         android:layout_height="wrap_content"  
89.         android:text="Show Selected"  
90.         android:id="@+id/button"  
91.         android:onClick="onclickbuttonMethod"  
92.         android:layout_gravity="center_horizontal" />  
93.   
94.   
95. </LinearLayout>  
Activity class
File: MainActivity.java

1. package example.javatpoint.com.radiobutton;  
2.   
3. import android.support.v7.app.AppCompatActivity;  
4. import android.os.Bundle;  
5. import android.view.View;  
6. import android.widget.Button;  
7. import android.widget.RadioButton;  
8. import android.widget.RadioGroup;  
9. import android.widget.Toast;  
10.   
11. public class MainActivity extends AppCompatActivity {  
12.     Button button;  
13.     RadioButton genderradioButton;  
14.     RadioGroup radioGroup;  
15.     @Override  
16.     protected void onCreate(Bundle savedInstanceState) {  
17.         super.onCreate(savedInstanceState);  
18.         setContentView(R.layout.activity_main);  
19.         radioGroup=(RadioGroup)findViewById(R.id.radioGroup);  
20.     }  
21.     public void onclickbuttonMethod(View v){  
22.         int selectedId = radioGroup.getCheckedRadioButtonId();  
23.         genderradioButton = (RadioButton) findViewById(selectedId);  
24.         if(selectedId==-1){  
25.             Toast.makeText(MainActivity.this,"Nothing selected", Toast.LENGTH_SHO
RT).show();  
26.         }  
27.         else{  
28.             Toast.makeText(MainActivity.this,genderradioButton.getText(), Toast.LENGTH_SH
ORT).show();  
29.         }  
30.   
31.     }  
32. }  

Android Dynamic RadioButton


Instead of creating RadioButton through drag and drop from palette, android also
facilitates you to create it programmatically (dynamically). For creating dynamic
RadioButton, we need to use android.view.ViewGroup.LayoutParams which
configures the width and height of views and
implements setOnCheckedChangeListener() method of RadioGroup class.
Example of Dynamic RadioButton
Let's see an example of Dynamic RadioButton.

activity_main.xml
File: activity_main.xml

1. <?xml version="1.0" encoding="utf-8"?>  
2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
3.     xmlns:tools="http://schemas.android.com/tools"  
4.     android:layout_width="match_parent"  
5.     android:layout_height="match_parent"  
6.     android:paddingBottom="@dimen/activity_vertical_margin"  
7.     android:paddingLeft="@dimen/activity_horizontal_margin"  
8.     android:paddingRight="@dimen/activity_horizontal_margin"  
9.     android:paddingTop="@dimen/activity_vertical_margin"  
10.     android:id="@+id/relativeLayout"  
11.     tools:context="com.example.test.dynamicradiobutton.MainActivity">  
12.   
13. </RelativeLayout>  
Activity class
File: MainActivity.java

1. package com.example.test.dynamicradiobutton;  
2.   
3. import android.support.v7.app.AppCompatActivity;  
4. import android.os.Bundle;  
5. import android.widget.RadioButton;  
6. import android.widget.RadioGroup;  
7. import android.widget.RelativeLayout;  
8.   
9. import android.widget.RelativeLayout.LayoutParams;  
10. import android.widget.Toast;  
11.   
12. public class MainActivity extends AppCompatActivity {  
13.     RadioGroup rg;  
14.     RelativeLayout rl;  
15.     RadioButton rb1,rb2;  
16.   
17.     @Override  
18.     protected void onCreate(Bundle savedInstanceState) {  
19.         super.onCreate(savedInstanceState);  
20.         setContentView(R.layout.activity_main);  
21.   
22.         rg = new RadioGroup(this);  
23.         rl = (RelativeLayout) findViewById(R.id.relativeLayout);  
24.         rb1 = new RadioButton(this);  
25.         rb2 = new RadioButton(this);  
26.   
27.         rb1.setText("Male");  
28.         rb2.setText("Female");  
29.         rg.addView(rb1);  
30.         rg.addView(rb2);  
31.         rg.setOrientation(RadioGroup.HORIZONTAL);  
32.   
33.         RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams((i
nt) LayoutParams.WRAP_CONTENT,(int)LayoutParams.WRAP_CONTENT);  
34.         params.leftMargin =150;  
35.         params.topMargin = 100;  
36.   
37.         rg.setLayoutParams(params);  
38.         rl.addView(rg);  
39.   
40.         rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {  
41.             @Override  
42.             public void onCheckedChanged(RadioGroup group, int checkedId) {  
43.                 RadioButton radioButton = (RadioButton) findViewById(checkedId);  
44.                 Toast.makeText(getApplicationContext(),radioButton.getText(),Toast.LENGTH_L
ONG).show();  
45.             }  
46.         });  
47.     }  
48. }  

Android Spinner Example

Android Spinner is like the combox box 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 spinner.

Android Spinner class is the subclass of AsbSpinner class.


Android Spinner Example
In this example, we are going to display the country list. You need to
use ArrayAdapter class to store the country list.

Let's see the simple example of spinner in android.

activity_main.xml

Drag the Spinner from the pallete, now the activity_main.xml file will like this:

File: activity_main.xml

1. <?xml version="1.0" encoding="utf-8"?>  
2. <android.support.constraint.ConstraintLayout xmlns:android="http://
schemas.android.com/apk/res/android"  
3.     xmlns:app="http://schemas.android.com/apk/res-auto"  
4.     xmlns:tools="http://schemas.android.com/tools"  
5.     android:layout_width="match_parent"  
6.     android:layout_height="match_parent"  
7.     tools:context="example.javatpoint.com.spinner.MainActivity">  
8.   
9.     <Spinner  
10.         android:id="@+id/spinner"  
11.         android:layout_width="149dp"  
12.         android:layout_height="40dp"  
13.         android:layout_marginBottom="8dp"  
14.         android:layout_marginEnd="8dp"  
15.         android:layout_marginStart="8dp"  
16.         android:layout_marginTop="8dp"  
17.         app:layout_constraintBottom_toBottomOf="parent"  
18.         app:layout_constraintEnd_toEndOf="parent"  
19.         app:layout_constraintHorizontal_bias="0.502"  
20.         app:layout_constraintStart_toStartOf="parent"  
21.         app:layout_constraintTop_toTopOf="parent"  
22.         app:layout_constraintVertical_bias="0.498" />  
23.   
24. </android.support.constraint.ConstraintLayout>  

Activity class

Let's write the code to display item on the spinner and perform event handling.

File: MainActivity.java

1. package example.javatpoint.com.spinner;  
2.   
3. import android.support.v7.app.AppCompatActivity;  
4. import android.os.Bundle;  
5. import android.view.View;  
6. import android.widget.AdapterView;  
7. import android.widget.ArrayAdapter;  
8. import android.widget.Spinner;  
9. import android.widget.Toast;  
10.   
11. public class MainActivity extends AppCompatActivity implements  
12.         AdapterView.OnItemSelectedListener {  
13.     String[] country = { "India", "USA", "China", "Japan", "Other"};  
14.   
15.     @Override  
16.     protected void onCreate(Bundle savedInstanceState) {  
17.         super.onCreate(savedInstanceState);  
18.         setContentView(R.layout.activity_main);  
19.        //Getting the instance of Spinner and applying OnItemSelectedListener on it  
20.         Spinner spin = (Spinner) findViewById(R.id.spinner);  
21.         spin.setOnItemSelectedListener(this);  
22.   
23.         //Creating the ArrayAdapter instance having the country list  
24.         ArrayAdapter aa = new ArrayAdapter(this,android.R.layout.simple_spinner_item,cou
ntry);  
25.         aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_it
em);  
26.         //Setting the ArrayAdapter data on the Spinner  
27.         spin.setAdapter(aa);  
28.   
29.     }  
30.   
31.     //Performing action onItemSelected and onNothing selected  
32.     @Override  
33.     public void onItemSelected(AdapterView<?> arg0, View arg1, int position, lon
g id) {  
34.         Toast.makeText(getApplicationContext(),country[position] , Toast.LENGTH_LONG).sh
ow();  
35.     }  
36.     @Override  
37.     public void onNothingSelected(AdapterView<?> arg0) {  
38.         // TODO Auto-generated method stub  
39.     }  
40. }  

Android Resources Organizing & Accessing


There are many more items which you use to build a good Android application. Apart from
coding for the application, you take care of various other resources like static content that your
code uses, such as bitmaps, colors, layout definitions, user interface strings, animation
instructions, and more. These resources are always maintained separately in various sub-
directories under res/ directory of the project.
This tutorial will explain you how you can organize your application resources, specify
alternative resources and access them in your applications.

Organize resource in Android Studio


MyProject/
app/
manifest/
AndroidManifest.xml
java/
MyActivity.java
res/
drawable/
icon.png
layout/
activity_main.xml
info.xml
values/
strings.xml

Sr.No. Directory & Resource Type

1
anim/
XML files that define property animations. They are saved in res/anim/ folder and accessed from
the R.anim class.

2
color/
XML files that define a state list of colors. They are saved in res/color/ and accessed from
the R.color class.

3
drawable/
Image files like .png, .jpg, .gif or XML files that are compiled into bitmaps, state lists, shapes,
animation drawable. They are saved in res/drawable/ and accessed from the R.drawable class.

4
layout/
XML files that define a user interface layout. They are saved in res/layout/ and accessed from
the R.layout class.

5
menu/
XML files that define application menus, such as an Options Menu, Context Menu, or Sub Menu.
They are saved in res/menu/ and accessed from the R.menu class.

6
raw/
Arbitrary files to save in their raw form. You need to call Resources.openRawResource() with the
resource ID, which is R.raw.filename to open such raw files.

7
values/
XML files that contain simple values, such as strings, integers, and colors. For example, here are
some filename conventions for resources you can create in this directory −
 arrays.xml for resource arrays, and accessed from the R.array class.
 integers.xml for resource integers, and accessed from the R.integer class.
 bools.xml for resource boolean, and accessed from the R.bool class.
 colors.xml for color values, and accessed from the R.color class.
 dimens.xml for dimension values, and accessed from the R.dimen class.
 strings.xml for string values, and accessed from the R.string class.
 styles.xml for styles, and accessed from the R.style class.

8
xml/
Arbitrary XML files that can be read at runtime by calling Resources.getXML(). You can save
various configuration files here which will be used at run time.

Alternative Resources
Your application should provide alternative resources to support specific device configurations.
For example, you should include alternative drawable resources ( i.e.images ) for different
screen resolution and alternative string resources for different languages. At runtime, Android
detects the current device configuration and loads the appropriate resources for your
application.
To specify configuration-specific alternatives for a set of resources, follow the following steps −
 Create a new directory in res/ named in the form <resources_name>-
<config_qualifier>. Here resources_name will be any of the resources mentioned in
the above table, like layout, drawable etc. The qualifier will specify an individual
configuration for which these resources are to be used. You can check official
documentation for a complete list of qualifiers for different type of resources.
 Save the respective alternative resources in this new directory. The resource files must be
named exactly the same as the default resource files as shown in the below example, but
these files will have content specific to the alternative. For example though image file
name will be same but for high resolution screen, its resolution will be high.
Below is an example which specifies images for a default screen and alternative images for high
resolution screen.
MyProject/
app/
manifest/
AndroidManifest.xml
java/
MyActivity.java
res/
drawable/
icon.png
background.png
drawable-hdpi/
icon.png
background.png
layout/
activity_main.xml
info.xml
values/
strings.xml
Below is another example which specifies layout for a default language and alternative layout
for Arabic language.
MyProject/
app/
manifest/
AndroidManifest.xml
java/
MyActivity.java
res/
drawable/
icon.png
background.png
drawable-hdpi/
icon.png
background.png
layout/
activity_main.xml
info.xml
layout-ar/
main.xml
values/
strings.xml

Accessing Resources
During your application development you will need to access defined resources either in your
code, or in your layout XML files. Following section explains how to access your resources in
both the scenarios −
Accessing Resources in Code
When your Android application is compiled, a R class gets generated, which contains resource
IDs for all the resources available in your res/ directory. You can use R class to access that
resource using sub-directory and resource name or directly resource ID.
Example
To access res/drawable/myimage.png and set an ImageView you will use following code −
ImageView imageView = (ImageView) findViewById(R.id.myimageview);
imageView.setImageResource(R.drawable.myimage);
Here first line of the code make use of R.id.myimageview to get ImageView defined with
id myimageview in a Layout file. Second line of code makes use of R.drawable.myimage to get
an image with name myimage available in drawable sub-directory under /res.
Example
Consider next example where res/values/strings.xml has following definition −
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello, World!</string>
</resources>
Now you can set the text on a TextView object with ID msg using a resource ID as follows −
TextView msgTextView = (TextView) findViewById(R.id.msg);
msgTextView.setText(R.string.hello);
Example
Consider a layout res/layout/activity_main.xml with the following definition −
<?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="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, I am a TextView" />

<Button android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, I am a Button" />

</LinearLayout>
This application code will load this layout for an Activity, in the onCreate() method as follows

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
Accessing Resources in XML
Consider the following resource XML res/values/strings.xml file that includes a color resource
and a string resource −
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="opaque_red">#f00</color>
<string name="hello">Hello!</string>
</resources>
Now you can use these resources in the following layout file to set the text color and text string
as follows −
<?xml version="1.0" encoding="utf-8"?>
<EditText xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:textColor="@color/opaque_red"
android:text="@string/hello" />
Now if you will go through previous chapter once again where I have explained Hello
World! example, and I'm sure you will have better understanding on all the concepts explained
in this chapter. So I highly recommend to check previous chapter for working example and
check how I have used various resources at very basic level

The Strings File


The strings.xml file is located in the res/values folder and it contains all the text
that your application uses. For example, the names of buttons, labels,
default
text, and similar types of strings go into this file. This file is responsible for their
textual content. For example, a default string file will look like as following file:

<resources>
<string name="app_name">HelloWorld</string>
<string name="hello_world">Hello world!</string>
<string name="menu_settings">Settings</string>
<string name="title_activity_main">MainActivity</string>
</resources>

You might also like