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

Android Chapter 3

The document provides an overview of Android User Interface (UI) design, detailing various UI controls such as TextView, EditText, Button, ToggleButton, CheckBox, RadioButton, and ProgressBar. It explains the purpose and attributes of each control, emphasizing how they contribute to creating interactive applications. Additionally, it describes the methods for defining UI elements, either through XML or programmatically at runtime.

Uploaded by

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

Android Chapter 3

The document provides an overview of Android User Interface (UI) design, detailing various UI controls such as TextView, EditText, Button, ToggleButton, CheckBox, RadioButton, and ProgressBar. It explains the purpose and attributes of each control, emphasizing how they contribute to creating interactive applications. Additionally, it describes the methods for defining UI elements, either through XML or programmatically at runtime.

Uploaded by

ritenpanchasara
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 83

SHREE SWAMI VIVEKANAND COLLEGE

SURENDRANAGAR

Chapter :-3 Android User Interface Design

Introduction.

 In android ui or input controls are the interactive or View components which


are used to design the user interface of an application. In android we have a
wide variety of UI or input controls available, those
are TextView, EditText, Buttons, Checkbox, Progressbar, Spinners, etc.

 Generally, in android the user interface of an app is made with a collection


of View and ViewGroup objects.

 The View is a base class for all UI components in android and it is used to
create an interactive UI components and it responsible for event handling
and drawing.

 The ViewGroup is a subclass of View and it will act as a base class for layouts
and layout parameters. The ViewGroup will provide an invisible containers to
hold other Views or ViewGroups and to define the layout properties.

 To know more about View and ViewGroup in android applications, check


this Android View and ViewGroup.

 In android, we can define a UI or input controls in two ways, those are

 Declare UI elements in XML


 Create UI elements at runtime

1|Page
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

Android Different Types of UI Controls:

 We have a different type of UI controls available in android to


implement user interface for our android applications.

 Following are the commonly used UI or input controls in android


applications.

TextView EditText

Button ImageButton

ToggleButton CheckBox

RadioButton ProgressBar

Spinner TimePicker

DatePicker RatingBar

2|Page
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

(1) TextView :-
 In android, TextView is a user interface control which is used to display
the text to the user.

 Android TextView Attributes:-

Attribute Description

android: id It is used to uniquely identify the control

android:autoLink It will automatically found and convert urls and email


addresses as a clickable links.

android: ems It is used to make the textview be exactly this many ems
wide.

android:hint It is used to display the hint text when text is empty

android:width It makes the TextView be exactly this many pixels wide.

android:height It makes the TextView be exactly this many pixels tall.

android:text It is used to display the text.

android:textColor It is used to change the color of text.

android:gravity It is used to specify how to align the text by the view's x and
y axis.

3|Page
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

Attribute Description

android:maxWidth It is used to make the TextView be at most this many pixels


wide.

android:minWidth It is used to make the TextView be at least this many pixels


wide.

android:textSize It is used to specify the size of text.

android:textStyle It is used to change the style (bold, italic, bolditalic) of text.

android:textAllCaps It is used to present the text in all CAPS

android:typeface It is used to specify the Typeface (normal, sans, serif,


monospace) for the text

android:textColor It is used to change the color of text.

android:textColorHighlight It is used to change the color of text selection highlight.

android:textColorLink It is used to change the text color of links.

android:inputType It is used to specify the type of text being placed in a text


fields.

android:fontFamily It is used to specify the fontFamily for the text.

4|Page
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

Attribute Description

android:editable If we set, it specifies that this TextView has an input method.

2.EditText:-
 In android, EditText is a user interface control which is used to allow the
user to enter or modify the text. While using EditText control in our android
applications, we need to specify the type of data the text field can accept
using inputType attribute.

 For example, if it accept plain text, then we need to specify the inputType
as “text”. In case if EditText field is for password, then we need to specify
the inputType as “textPassword”.

 In android, EditText control is an extended version of TextView control with


an additional features and it is used to allow users to enter input values.

 Android EditText Attributes :-

Attribute Description

android:id It is used to uniquely identify the control

android:gravity It is used to specify how to align the text like left, right,
center, top, etc.

android:text It is used to set the text.

android:hint It is used to display the hint text when text is empty

5|Page
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

Attribute Description

android:textColor It is used to change the color of text.

android:textColorHint It is used to change the text color of hint text.

android:textSize It is used to specify the size of text.

android:textStyle It is used to change the style (bold, italic, bolditalic) of text.

android:background It is used to set the background color for edit text control

android:ems It is used to make the textview be exactly this many ems


wide.

android:width It makes the TextView be exactly this many pixels wide.

android:height It makes the TextView be exactly this many pixels tall.

android:maxWidth It is used to make the TextView be at most this many pixels


wide.

android:minWidth It is used to make the TextView be at least this many pixels


wide.

android:textAllCaps It is used to present the text in all CAPS

6|Page
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

Attribute Description

android:typeface It is used to specify the Typeface (normal, sans, serif,


monospace) for the text.

android:textColorHighligt It is used to change the color of text selection highlight.

android:inputType It is used to specify the type of text being placed in a text


fields.

android:fontFamily It is used to specify the fontFamily for the text.

android:editable If we set false, EditText won't allow us to enter or modify


text

3. Button:-

 In android, Button is a user interface control which is used to perform an


action whenever the user click or tap on it.

 Generally, Buttons in android will contains a text or an icon or both and


perform an action when user touches it.

 In android, we have a different type of buttons available to use based on


our requirements, those are ImageButton, ToggleButton, RadioButton.

 Android Button Control Attributes:-

7|Page
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

Attribute Description

android:id It is used to uniquely identify the control

android:gravity It is used to specify how to align the text like left, right,
center, top, etc.

android:text It is used to set the text.

android:textColor It is used to change the color of text.

android:textSize It is used to specify the size of text.

android:textStyle It is used to change the style (bold, italic, bolditalic) of


text.

android:background It is used to set the background color for button control.

android:padding It is used to set the padding from left, right, top and
bottom.

android:drawableBottom It’s a drawable to be drawn to the below of text.

android:drawableRight It’s a drawable to be drawn to the right of text.

android:drawableLeft It’s a drawable to be drawn to the left of text.

4.ImageButton:-
8|Page
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

 In android, Image Button is a user interface control which is used to display


a button with image and to perform an action when user click or tap on it.

 By default, the ImageButton looks same as normal button and it perform an


action when user click or touches it, but only difference is we will add a
custom image to the button instead of text.

 Android ImageButton Control Attributes:-

Attribute Description

android:id It is used to uniquely identify the control

android:src It is used to specify the source file of image

android:background It is used to set the background color for an image button


control.

android:padding It is used to set the padding from left, right, top and bottom
of image button.

android:baseline It is used to set offset of the baseline within the view.

(5)Toggle Button:-

 In android, Toggle Button is a user interface control which is used to


display ON (Checked) or OFF (Unchecked) states as a button with a light
indicator.

9|Page
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

 The ToggleButton is useful for the users to change the settings between
two states either ON or OFF. We can add a ToggleButton to our application
layout by using ToggleButton object.

 Following is the pictorial representation of using ToggleButton in android


applications.

 By default, the android ToggleButton will be in OFF (Unchecked) state. We


can change the default state of ToggleButton by using android:checked
attribute.

 In case, if we want to change the state of ToggleButton to ON (Checked),


then we need to set android:checked = “true”in our XML layout file.

 Android ToggleButton Control Attributes:-

Attribute Description

android:id It is used to uniquely identify the control

android:checked It is used to specify the current state of toggle button

android:gravity It is used to specify how to align the text like left, right,
center, top, etc.

android:text It is used to set the text.

10 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

Attribute Description

android:textOn It is used to set the text when toggle button is in ON /


Checked state.

android:textOff It is used to set the text when toggle button is in OFF /


Unchecked state.

android:textColor It is used to change the color of text.

android:textSize It is used to specify the size of text.

android:textStyle It is used to change the style (bold, italic, bolditalic) of


text.

android:background It is used to set the background color for toggle button


control.

android:padding It is used to set the padding from left, right, top and
bottom.

android:drawableBottom It’s a drawable to be drawn to the below of text.

android:drawableRight It’s a drawable to be drawn to the right of text.

android:drawableLeft It’s a drawable to be drawn to the left of text.

(6) checkbox:-

11 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

 In android, CheckBox is a two states button that can be either checked (ON)
or unchecked (OFF) and it will allow users to toggle between the two states
(ON / OFF) based on the requirements.

 Generally, we can use multiple CheckBox controls in android application to


allow users to select one or more options from the set of values.

 By default, the android CheckBox will be in OFF (Unchecked) state. We can


change the default state of CheckBox by using android:checked attribute.

 In case, if we want to change the state of CheckBox to ON (Checked), then


we need to set android:checked = “true” in our XML layout file.

 Android CheckBox Control Attributes:-

Attribute Description

android:id It is used to uniquely identify the control

android:checked It is used to specify the current state of checkbox

android:gravity It is used to specify how to align the text like left, right,
center, top, etc.

android:text It is used to set the text for checkbox.

12 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

Attribute Description

android:textColor It is used to change the color of text.

android:textSize It is used to specify the size of text.

android:textStyle It is used to change the style (bold, italic, bolditalic) of text.

android:background It is used to set the background color for checkbox control.

android:padding It is used to set the padding from left, right, top and bottom.

android:onClick It’s a name of the method to invoke when the checkbox


clicked.

android:visibility It is used to control the visibility of control.

(7) RadioButton :-
 In android, Radio Button is a two states button that can be either checked
or unchecked and it’s a same as CheckBox control, except that it will allow
only one option to select from the group of options.

 The user can press or click on radio button to make it select. In


android, CheckBox control allow users to change the state of control either
Checked or Unchecked but the radiobutton cannot be unchecked once it is
checked.

 Generally, we can use RadioButton controls in android application to allow


users to select only one option from the set of values.

13 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

Attribute Description

android:id It is used to uniquely identify the control

android:checked It is used to specify the current state of radio button

android:gravity It is used to specify how to align the text like left, right, center,
top, etc.

android:text It is used to set the text for radio button.

android:textColor It is used to change the color of text.

android:textSize It is used to specify the size of text.

android:textStyle It is used to change the style (bold, italic, bolditalic) of text.

android:background It is used to set the background color for radio button control.

android:padding It is used to set the padding from left, right, top and bottom.

android:onClick It’s a name of the method to invoke when the radio button
clicked.

android:visibility It is used to control the visibility of control.

14 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

(8) ProgressBar:-

 In android, ProgressBar is a user interface control which is used to indicate


the progress of an operation. For example, downloading a file, uploading a
file.

Attribute Description

android:id It is used to uniquely identify the control

android:minHeight It is used to set the height of progress bar.

android:minWidth It is used to set the width of progress bar.

android:max It is used to set the maximum value of progress bar.

android:progress It is used to set the default progress value between 0 and max. It
must be an integer

value.

15 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

(9) Spinner Control:-

 In android, Spinner is a view which allow a user to select one value from the
list of values. The spinner in android will behave same like dropdown list in
other programming languages.
 the android spinners will provide a quick way to select one item from the
list of values and it will show a dropdown menu with a list of all values
when we click or tap on it.

 By default, the android spinner will show its currently selected value and by
using Adapter we can bind the items to spinner object.
 We can populate our Spinner control with list of choices by defining
an ArrayAdapter in our Activity file.

 Generally, the Adapter pulls data from a sources such as an array or


database and converts each item into a result view and that’s placed into
the list.

 Android Adapter
 In android, Adapter will act as an intermediate between the data sources
and adapter views such as ListView, Gridviewto fill the data into adapter
views. The adapter will hold the data and iterates through an items in data
set and generate the views for each item in the list.

Adapter Description

ArrayAdapter It will expects an Array or List as input.

16 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

Adapter Description

CurosrAdapter It will accepts an instance of cursor as an input.

SimpleAdapter It will accepts a static data defined in the resources.

BaseAdapter It is a generic implementation for all three adapter types and it can be
used for

ListView, Gridview or Spinners based on our requirements

(10) TimePicker:-

 In android, TimePicker is a widget for selecting the time of day, in either 24-
hour or AM/PM mode.

 If we use TimePicker in our application, it will ensure that the users will
select a valid time for the day.

 Android TimePicker Control Attributes :-

Attribute Description

android:id It is used to uniquely identify the control

android:timePickerMode It is used to specify timepicker mode, either spinner or clock

android:background It is used to set the background color for date picker.

17 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

Attribute Description

android:padding It is used to set the padding for left, right, top or bottom of
date picker.

(11) DatePicker:-

 In android, DatePicker is a control which will allow users to select the date
by day, month and year in our application user interface.

 If we use DatePicker in our application, it will ensure that the users will
select a valid date.

 Android DatePicker Control Attributes

Attribute Description

android:id It is used to uniquely identify the control

android:datePickerMode It is used to specify datepicker mode either spinner or


calendar

android:background It is used to set the background color for date picker.

android:padding It is used to set the padding for left, right, top or bottom
of date picker.

18 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

TextView, Button and ExitText Example

activity_main.xml
In the activity_main.xml file add the following code

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout 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="example.javatpoint.com.kotlintextviewedittext.MainActivity">

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="12dp"
android:text="TextView and EditText"
android:gravity="center"
android:textAppearance="@style/Base.TextAppearance.AppCompat.Large"/>
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView1"
android:layout_marginTop="90dp"
android:layout_marginLeft="20dp"
android:layout_marginStart="20dp"
android:textSize="16sp"
android:text="Provide Input" />

<TextView

19 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView2"
android:layout_marginTop="50dp"
android:layout_marginLeft="20dp"
android:layout_marginStart="20dp"
android:textSize="16sp"
android:text="Display Output" />

<EditText
android:id="@+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/textView2"
android:layout_alignBottom="@+id/textView2"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_marginEnd="21dp"
android:layout_marginRight="21dp"
android:ems="10"
android:inputType="textPersonName"
android:text="" />

<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText"
android:layout_alignStart="@+id/editText"
android:layout_alignTop="@+id/textView3"
android:textSize="16sp"
android:text="TextView" />

<Button

20 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView4"
android:layout_centerHorizontal="true"
android:layout_marginTop="112dp"
android:text="Click Button" />

<TextView
android:id="@+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignEnd="@+id/editText"
android:layout_alignRight="@+id/editText"
android:layout_centerVertical="true"
android:text="reset output text" />
</RelativeLayout>

MainActivity.kt

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.widget.TextView
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

21 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

button.setOnClickListener(){
val inputValue: String = editText.text.toString()
if (inputValue == null || inputValue.trim()==""){
Toast.makeText(this,"please input data, edit text cannot be blank",Toast.LENGT
H_LONG).show()
}else{
textView4.setText(inputValue).toString()
}
}
textView5.setOnClickListener(){
if (textView4.text.toString() == null || textView4.text.toString().trim()==""){
Toast.makeText(this,"clicked on reset textView,\n output textView already reset",Toast
.LENGTH_LONG).show()
}else{
textView4.setText("").toString()
}
}
editText.addTextChangedListener(object: TextWatcher{
override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
// TODO("not implemented") //To change body of created functions use File | S
ettings | File Templates.
Toast.makeText(applicationContext,"executed before making any change over EditText
",Toast.LENGTH_SHORT).show()
}

override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
// TODO("not implemented") //To change body of created functions use File | Settings |
File Templates.
Toast.makeText(applicationContext,"executed while making any change over E
ditText",Toast.LENGTH_SHORT).show()
}
override fun afterTextChanged(p0: Editable?) {
// TODO("not implemented") //To change body of created functions use File | Settings |
File Templates.
Toast.makeText(applicationContext,"executed after change made over EditText
",Toast.LENGTH_SHORT).show()

22 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

}
})
}
}

Android Spinner Example :

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout 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:orientation="vertical"
android:id="@+id/linearLayout" android:gravity="center" tools:context=".MainActivity">

<Spinner
android:id="@+id/mySpinner"
android:layout_width="match_parent"
android:spinnerMode="dialog"
android:layout_height="wrap_content" />

</LinearLayout>

23 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

Spinner XML Code

The code for spinner_right_aligned.xml is given below


.
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="end"
android:padding="15dp"
android:textAlignment="gravity"
android:textColor="@color/colorPrimary"
android:textSize="16sp"
/>

MainActivity Kotlin Code

The code for the MainActivity.kt class is given below.

package net.androidly.androidspinnerkotlin

import android.content.Context
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.widget.*
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity(), AdapterView.OnItemSelectedListener {

var languages = arrayOf("Java", "PHP", "Kotlin", "Javascript", "Python", "Swift")


val NEW_SPINNER_ID = 1

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

var aa = ArrayAdapter(this, android.R.layout.simple_spinner_item, languages)


aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)

24 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

with(mySpinner)
{
adapter = aa
setSelection(0, false)
onItemSelectedListener = this@MainActivity
prompt = "Select your favourite language"
gravity = Gravity.CENTER

val spinner = Spinner(this)


spinner.id = NEW_SPINNER_ID

val ll = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT)

ll.setMargins(10, 40, 10, 10)


linearLayout.addView(spinner)

aa = ArrayAdapter(this, R.layout.spinner_right_aligned, languages)


aa.setDropDownViewResource(R.layout.spinner_right_aligned)

with(spinner)
{
adapter = aa
setSelection(0, false)
onItemSelectedListener = this@MainActivity
layoutParams = ll
prompt = "Select your favourite language"
setPopupBackgroundResource(R.color.material_grey_600)

override fun onNothingSelected(parent: AdapterView<*>?) {


showToast(message = "Nothing selected")
}

override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id:


Long) {

when (view?.id) {
1 -> showToast(message = "Spinner 2 Position:${position} and language:
${languages[position]}")
else -> {

25 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

showToast(message = "Spinner 1 Position:${position} and language:


${languages[position]}")
}
}
}

private fun showToast(context: Context = applicationContext, message: String, duration:


Int = Toast.LENGTH_LONG) {
Toast.makeText(context, message, duration).show()
}
}

26 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

Toggle Button Example :-

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>


<androidx.constraintlayout.widget.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=".MainActivity">

<ToggleButton
android:id="@+id/toggleButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.kt file

package com.example.togglebuttonsample
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import android.widget.ToggleButton

27 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

val toggle: ToggleButton = findViewById(R.id.toggleButton)


toggle.setOnCheckedChangeListener { _, isChecked ->
Toast.makeText(this, if(isChecked) "Geek Mode ON" else "Geek Mode OFF",
Toast.LENGTH_SHORT).show()
}
}
}

28 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

RatinBar Example :-

XML Layout Code

The code for the layout activity_main.xml is given below.

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="16dp"
android:gravity="center"
android:orientation="vertical"
tools:context=".MainActivity">

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:textSize="32sp"/>

<RatingBar
android:id="@+id/ratingBar1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:rating="1"
android:stepSize="1" />

<RatingBar
android:id="@+id/ratingBar2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:numStars="5" />

<RatingBar
android:id="@+id/ratingBar3"

29 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@color/colorPrimary"
android:numStars="3"
android:rating="0.4"
android:secondaryProgressTint="@android:color/white"
android:stepSize="0.2" />

<RatingBar
android:id="@+id/ratingBar4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:numStars="5"
android:progressBackgroundTint="@android:color/black"
android:progressTint="@android:color/holo_green_dark"
android:rating="1"
android:stepSize="0.5" />

<RatingBar
android:id="@+id/ratingBar5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:numStars="5"
android:progressBackgroundTint="@android:color/white"
android:progressTint="@android:color/holo_green_dark"
android:rating="2.5"
android:secondaryProgressTint="@color/colorPrimaryDark"
android:stepSize="0.5" />

<RatingBar
android:id="@+id/ratingBar6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:isIndicator="true"
android:numStars="5"
android:rating="0.7"
android:stepSize="0.7" />

<RatingBar
android:id="@+id/ratingBar7"
style="@android:style/Widget.Material.RatingBar.Small"
android:layout_width="wrap_content"
android:layout_height="wrap_content"

30 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

android:layout_marginTop="8dp"
android:isIndicator="false"
android:numStars="5"
android:rating="1"
android:stepSize="0.5" />

<RatingBar
android:id="@+id/ratingBar8"
style="@style/CustomRatingBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:numStars="5"
android:progressBackgroundTint="@android:color/holo_orange_dark" />

<RatingBar
android:id="@+id/ratingBar9"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:numStars="5"
android:progressBackgroundTint="@android:color/black"
android:progressDrawable="@drawable/ic_action_happy"
android:progressTint="@color/colorPrimary"
android:rating="1" />

</LinearLayout>

Add the following code in the styles.xml file.

<style name="CustomRatingBar" parent="Widget.AppCompat.RatingBar">


<item name="android:progressDrawable">@drawable/custom_ratingbar</item>
<item name="colorControlNormal">#f57c00</item>
<item name="colorControlActivated">#c51162</item>
</style>

We’ve created a custom_ratingbar.xml drawable as well.

<?xml version="1.0" encoding="utf-8"?>


<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@android:id/background">
<bitmap

31 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

android:src="@drawable/ic_action_happy"
android:tint="?attr/colorControlNormal" />
</item>
<item android:id="@android:id/secondaryProgress">
<bitmap
android:src="@drawable/ic_action_happy"
android:tint="?attr/colorControlHighlight" />
</item>
<item android:id="@android:id/progress">
<bitmap
android:src="@drawable/ic_action_happy"
android:tint="?attr/colorControlActivated" />
</item>
</layer-list>

MainActivity.kt file

package net.androidly.androidlyratingbar
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.RatingBar
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity(), RatingBar.OnRatingBarChangeListener {

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

ratingBar1.onRatingBarChangeListener = this
ratingBar2.onRatingBarChangeListener = this
ratingBar3.onRatingBarChangeListener = this
ratingBar4.onRatingBarChangeListener = this
ratingBar5.onRatingBarChangeListener = this
ratingBar6.onRatingBarChangeListener = this
ratingBar7.onRatingBarChangeListener = this
ratingBar8.onRatingBarChangeListener = this
ratingBar9.onRatingBarChangeListener = this

}
override fun onRatingChanged(p0: RatingBar?, p1: Float, p2: Boolean) {

textView.text = "$p1"
}
}

32 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

33 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

ProgressBar Control :-
Xml Layout file
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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">

<Button
android:id="@+id/Progress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Show Progress"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Mainactivity.kt file

import android.app.ProgressDialog
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_progress__dialog.*

class MainActivity : AppCompatActivity() {


override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

34 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

val progressDialog = ProgressDialog(this)


progressDialog.setTitle("Please Wait")
progressDialog.setMessage("Loading ...")
Progress.setOnClickListener { progressDialog.show() }
}

35 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

Image Button

XML Layout Code

The code for the activity_main.xml class is given below.

<?xml version="1.0" encoding="utf-8"?>


<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">

<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:src="@drawable/sample_1" />

<ImageButton
android:id="@+id/imageButton"
android:layout_width="wrap_content"
android:src="@android:drawable/ic_menu_set_as"
android:layout_gravity="bottom|center_horizontal"
android:layout_height="wrap_content" />

</FrameLayout>

Mainactivity.kt file

package net.androidly.androidiyimageviewsbuttons

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.view.View
import android.widget.ImageButton
import android.widget.ImageView

36 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity(), View.OnClickListener {

val sampleDrawables = intArrayOf(R.drawable.sample_1, R.drawable.sample_2,


R.drawable.sample_3)

var i = 0

val scaleType = arrayListOf(ImageView.ScaleType.CENTER_CROP,


ImageView.ScaleType.FIT_CENTER, ImageView.ScaleType.CENTER_CROP,
ImageView.ScaleType.FIT_XY)

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

imageView.setOnClickListener(this)
imageButton.setOnClickListener(this)
}

override fun onClick(p0: View?) {


when (p0) {
is ImageButton -> if (i == sampleDrawables.size) {
i=0
imageView.setImageResource(sampleDrawables[i])
imageView.colorFilter = null
i++
} else {
imageView.setImageResource(sampleDrawables[i])
imageView.colorFilter = null

i++
}
is ImageView -> {
imageView.setColorFilter(ContextCompat.getColor(this, R.color.myColor))
imageView.scaleType = scaleType.shuffled().take(1)[0]
}

else -> Toast.makeText(applicationContext, "Neither ImageView nor ImageButton",


Toast.LENGTH_LONG).show()
}

37 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

38 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

CheckBox Control :-

Create new project


1. Click on File, then New => New Project.
2. Choose “Empty Activity” for the project template.
3. Select language as Kotlin.
4. Select the minimum SDK as per your need.

Open activity_main.xml file

<?xml version="1.0" encoding="utf-8"?>


<androidx.constraintlayout.widget.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"
android:background="#168BC34A"
tools:context=".MainActivity" >

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="@font/roboto"
android:text="@string/Heading"
android:textAlignment="center"
android:textColor="@android:color/holo_green_dark"
android:textSize="36sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"

39 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.17000002" />

<LinearLayout
android:id="@+id/checkBox_container"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView"
app:layout_constraintVertical_bias="0.18">

<CheckBox
android:id="@+id/checkBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="@font/roboto"
android:text="@string/checkBox1_text"
android:textSize="18sp"
android:padding="7dp"/>

<CheckBox
android:id="@+id/checkBox2"
android:layout_width="match_parent"
android:layout_height="wrap_content"

40 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

android:fontFamily="@font/roboto"
android:text="@string/checkBox2_text"
android:textSize="18sp"
android:padding="7dp"/>

<CheckBox
android:id="@+id/checkBox3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="@font/roboto"
android:text="@string/checkBox3_text"
android:textSize="18sp"
android:padding="7dp"/>

<CheckBox
android:id="@+id/checkBox4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="@font/roboto"
android:text="@string/checkBox4_text"
android:textSize="18sp"
android:padding="7dp"/>

<CheckBox
android:id="@+id/checkBox5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="@font/roboto"
android:text="@string/checkBox5_text"

41 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

android:textSize="18sp"
android:padding="7dp"/>
</LinearLayout>

<Button
android:id="@+id/submitButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#AB4CAF50"
android:fontFamily="@font/roboto"
android:text="@string/submitButton"
android:textSize="18sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/checkBox_container"
app:layout_constraintVertical_bias="0.23000002" />
</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.kt file

package com.example.checkboxinkotlin

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.Toast

42 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

class MainActivity : AppCompatActivity() {


override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

// Assigning id of the submit button


val button : Button = findViewById(R.id.submitButton)

// Actions to be performed
// when Submit button is clicked
button.setOnClickListener{

// Display toast message


Toast.makeText(applicationContext,
"Your response has been recorded", Toast.LENGTH_LONG).show()
}
}
}

strings.xml file
All the strings which are used in the activity, from the text view to the Checkbox texts are
listed in this file.

<resources>
<string name="app_name">CheckBox in Kotlin</string>
<string name="Heading">Services provided by GeeksforGeeks</string>
<string name="checkBox1">Coding contests</string>
<string name="checkBox2_text">Civil Engineering Courses</string>
<string name="checkBox1_text">Coding Contests</string>
<string name="checkBox3_text">Computer Science Courses</string>

43 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

<string name="checkBox4_text">Company specific coding questions</string>


<string name="checkBox5_text">Download movies</string>
<string name="submitButton">SUBMIT</string>
</resources>

AndroidManifest.xml file

Below is the code for AndroidManifest.xml file.

<?xml version="1.0" encoding="utf-8"?>


<manifest xmlns:android="http:// schemas.android.com/apk/res/android"
package="com.example.checkboxinkotlin">

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />


</intent-filter>
</activity>
</application>

</manifest>

44 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

RadioButton Control :-

Layout Code

The code for the activity_main.xml layout is given below:

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">

<RadioButton
android:id="@+id/androidlyRadioButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"

45 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

android:gravity="center"
android:onClick="androidlyRadioButton"
android:text="Androidly RadioButtons"
android:textSize="18sp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Which layout has child views on top of each other?"
android:textSize="20sp" />

<RadioGroup
android:id="@+id/firstRg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:contentDescription="Layouts"
android:orientation="vertical">

<RadioButton
android:id="@+id/radioButton1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="LinearLayout"
android:textSize="18sp" />

<RadioButton
android:id="@+id/radioButton2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:buttonTint="@color/colorPrimary"
android:text="RelativeLayout"
android:textSize="18sp" />

<RadioButton
android:id="@+id/radioButton3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="FrameLayout"
android:textColor="#99cc00"
android:textSize="18sp" />

<RadioButton
android:id="@+id/radioButton4"
android:layout_width="fill_parent"

46 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

android:layout_height="wrap_content"
android:text="TableLayout"
android:textSize="18sp" />

</RadioGroup>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Which of the following are clickable?"
android:textSize="20sp" />

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Clear Groups" />

</LinearLayout>

MainActivity.kt Code

The code for the MainActivity.kt class is given below:

package net.androidly.androidlyradiobuttons

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.*
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.activity_main.view.*

class MainActivity : AppCompatActivity(), RadioGroup.OnCheckedChangeListener {

val buttonTexts = arrayListOf("Buttons", "Text", "Both")

val ID = 101

47 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

val secondRg = RadioGroup(this)


secondRg.orientation = RadioGroup.HORIZONTAL
secondRg.weightSum = 3f
secondRg.id = ID
secondRg.contentDescription = "Widgets"
secondRg.setOnCheckedChangeListener(this)
linearLayout.firstRg.setOnCheckedChangeListener(this)

val p = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT)
p.weight = 0.5f

for (i in 0 until buttonTexts.size) {


val radioButton = RadioButton(this)
radioButton.apply {
text = buttonTexts[i]
id = i
layoutParams = p
}
secondRg.addView(radioButton)
}

linearLayout.addView(secondRg, 4)

button.setOnClickListener {
secondRg.clearCheck()
linearLayout.firstRg.clearCheck()
}
}

override fun onCheckedChanged(group: RadioGroup?, checkId: Int) {


val checkedRadioButton = group?.findViewById(group.checkedRadioButtonId) as?
RadioButton
checkedRadioButton?.let {

if (checkedRadioButton.isChecked)
Toast.makeText(applicationContext, "RadioGroup: ${group?.contentDescription}
RadioButton: ${checkedRadioButton?.text}", Toast.LENGTH_LONG).show()
}

48 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

fun androidlyRadioButton(view: View) {

val radioButton = view as RadioButton


Toast.makeText(applicationContext, "Radio Button: ${radioButton.text}",
Toast.LENGTH_LONG).show()
}
}

Designing user interface with layouts


There are mainly four types of layout available in android.

Linear Layout
Relative
Table
Frame

Other is Layout with using adapter

ListView
GridView

Android Linear Layout:-


Android LinearLayout is a view group that aligns all children in
eithervertically or horizontally.

49 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

LINEAR LAYOUT

LinearLayout Attributes

Following are the important attributes specific to LinearLayout −

Sr.No Attribute & Description

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

android:baselineAligned
2
This must be a boolean value, either "true" or "false" and prevents the layout from aligning
its children's baselines.

android:baselineAlignedChildIndex
3
When a linear layout is part of another layout that is baseline aligned, it can specify which
of its children to baseline align.

android:divider
4
This is drawable to use as a vertical divider between buttons. You use a color value, in the
form of "#rgb", "#argb", "#rrggbb", or "#aarrggbb".

android:gravity
5
This specifies how an object should position its content, on both the X and Y axes. Possible
values are top, bottom, left, right, center, center_vertical, center_horizontal etc.

6 android:orientation

50 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

This specifies the direction of arrangement and you will use "horizontal" for a row,
"vertical" for a column. The default is horizontal.

android:weightSum
7
Sum up of child weight

<LinearLayout xmlns:android=http://schemas.android.com/apk/res/android
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

Now let's change the orientation of Layout as


android:orientation="horizontal" and try to run the same application, it
will give following screen −

51 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

Android Relative Layout:-

Android RelativeLayout enables you to specify how child views are positioned
relative to each other. The position of each view can be specified as relative
to sibling elements or relative to the parent.

RelativeLayout Attributes
Following are the important attributes specific to RelativeLayout −

Sr.No. Attribute & Description

1
android:id

This is the ID which uniquely identifies the layout.

2
android:gravity

This specifies how an object should position its content, on both the X and Y axes. Possible
values are top, bottom, left, right, center, center_vertical, center_horizontal etc.

3
android:ignoreGravity

This indicates what view should not be affected by gravity.

Using RelativeLayout, you can align two elements by right border, or make
one below another, centered in the screen, centered left, and so on. By
default, all child views are drawn at the top-left of the layout, so you must

52 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

define the position of each view using the various layout properties available
fromRelativeLayout.LayoutParams and few of the important attributes are
given below −

Sr.No. Attribute & Description

1
android:layout_above

Positions the bottom edge of this view above the given anchor view ID and must be a
reference to another resource, in the form "@[+][package:]type:name"

2
android:layout_alignBottom

Makes the bottom edge of this view match the bottom edge of the given anchor view ID
and must be a reference to another resource, in the form "@[+][package:]type:name".

3
android:layout_alignLeft

Makes the left edge of this view match the left edge of the given anchor view ID and must
be a reference to another resource, in the form "@[+][package:]type:name".

4
android:layout_alignParentBottom

If true, makes the bottom edge of this view match the bottom edge of the parent. Must be
a boolean value, either "true" or "false".

5
android:layout_alignParentEnd

If true, makes the end edge of this view match the end edge of the parent. Must be a
boolean value, either "true" or "false".

6
android:layout_alignParentLeft

53 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

If true, makes the left edge of this view match the left edge of the parent. Must be a boolean
value, either "true" or "false".

7
android:layout_alignParentRight

If true, makes the right edge of this view match the right edge of the parent. Must be a
boolean value, either "true" or "false".

8
android:layout_alignParentStart

If true, makes the start edge of this view match the start edge of the parent. Must be a
boolean value, either "true" or "false".

9
android:layout_alignParentTop

If true, makes the top edge of this view match the top edge of the parent. Must be a boolean
value, either "true" or "false".

10
android:layout_alignRight

Makes the right edge of this view match the right edge of the given anchor view ID and
must be a reference to another resource, in the form "@[+][package:]type:name".

11
android:layout_alignStart

Makes the start edge of this view match the start edge of the given anchor view ID and
must be a reference to another resource, in the form "@[+][package:]type:name".

12
android:layout_alignTop

Makes the top edge of this view match the top edge of the given anchor view ID and must
be a reference to another resource, in the form "@[+][package:]type:name".

54 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

13
android:layout_below

Positions the top edge of this view below the given anchor view ID and must be a reference
to another resource, in the form "@[+][package:]type:name".

14
android:layout_centerHorizontal

If true, centers this child horizontally within its parent. Must be a boolean value, either
"true" or "false".

15
android:layout_centerInParent

If true, centers this child horizontally and vertically within its parent. Must be a boolean
value, either "true" or "false".

16
android:layout_centerVertical

If true, centers this child vertically within its parent. Must be a boolean value, either "true"
or "false".

17
android:layout_toEndOf

Positions the start edge of this view to the end of the given anchor view ID and must be a
reference to another resource, in the form "@[+][package:]type:name".

18
android:layout_toLeftOf

Positions the right edge of this view to the left of the given anchor view ID and must be a
reference to another resource, in the form "@[+][package:]type:name".

19
android:layout_toRightOf

Positions the left edge of this view to the right of the given anchor view ID and must be a
reference to another resource, in the form "@[+][package:]type:name".

55 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

20
android:layout_toStartOf

Positions the end edge of this view to the start of the given anchor view ID and must be a
reference to another resource, in the form "@[+][package:]type:name".

Android Table Layout:-

ndroid TableLayout going to be arranged groups of views into rows and


columns. You will use the <TableRow> element to build a row in the table.
Each row has zero or more cells; each cell can hold one View object.

TableLayout containers do not display border lines for their rows, columns, or
cells.

TableLayout Attributes
Following are the important attributes specific to TableLayout −

56 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

Sr.No. Attribute & Description

1
android:id

This is the ID which uniquely identifies the layout.

2
android:collapseColumns

This specifies the zero-based index of the columns to collapse. The column indices must
be separated by a comma: 1, 2, 5.

3
android:collapseColumns

The zero-based index of the columns to shrink. The column indices must be separated by
a comma: 1, 2, 5.

4
android:stretchColumns

The zero-based index of the columns to stretch. The column indices must be separated by
a comma: 1, 2, 5.

TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

<TableRow

android:layout_width="fill_parent"
android:layout_height="fill_parent">

<TextView
android:text="Time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"

57 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

android:layout_column="1" />

<TextClock
android:layout_width="wrap_content"

android:layout_height="wrap_content"
android:id="@+id/textClock"
android:layout_column="2" />

</TableRow>

<TableRow>

<TextView
android:text="First Name"

android:layout_width="wrap_content"
android:layout_height="wrap_content"

android:layout_column="1" />

<EditText
android:width="200px"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</TableRow>

<TableRow>

<TextView
android:text="Last Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1" />

58 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

<EditText
android:width="100px"

android:layout_width="wrap_content"
android:layout_height="wrap_content" />

</TableRow>

<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent">

<RatingBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/ratingBar"

android:layout_column="2" />
</TableRow>

<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>

<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent">

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit"
android:id="@+id/button"
android:layout_column="2" />

</TableRow>

59 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

</TableLayout>

Following will be the content of res/values/strings.xml to define two new


constants −

<?xml version="1.0" encoding="utf-8"?>


<resources>
<string name="app_name">HelloWorld</string>
<string name="action_settings">Settings</string>

</resources>

Let's try to run our modified Hello World! application we just modified. I
assume you had created your AVD while doing environment setup. To run the
app from Android Studio, open one of your project's activity files and click
Run icon from the toolbar. Android studio installs the app on your AVD and
starts it and if everything is fine with your setup and application, it will display
following Emulator window −

60 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

Android Frame Layout :-


Frame Layout is designed to block out an area on the screen to display a
single item. Generally, FrameLayout should be used to hold a single child view,
because it can be difficult to organize child views in a way that's scalable to
different screen sizes without the children overlapping each other.

FrameLayout Attributes
Following are the important attributes specific to FrameLayout −

Sr.No Attribute & Description

1
android:id

This is the ID which uniquely identifies the layout.

2
android:foreground

This defines the drawable to draw over the content and possible values may be a color
value, in the form of "#rgb", "#argb", "#rrggbb", or "#aarrggbb".

3
android:foregroundGravity

Defines the gravity to apply to the foreground drawable. The gravity defaults to fill.
Possible values are top, bottom, left, right, center, center_vertical, center_horizontal etc.

4
android:measureAllChildren

Determines whether to measure all children or just those in the VISIBLE or INVISIBLE
state when measuring. Defaults to false.

61 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

Android List View

Android ListView is a view which groups several items and display them in
vertical scrollable list. The list items are automatically inserted to the list using
an Adapter that pulls content from a source such as an array or database.

LIST VIEW
An adapter actually bridges between UI components and the data source that
fill data into UI Component. Adapter holds the data and send the data to
adapter view, the view can takes the data from adapter view and shows the
data on different views like as spinner, list view, grid view etc.

The ListView and GridView are subclasses of AdapterView and they can
be populated by binding them to an Adapter, which retrieves data from an
external source and creates a View that represents each data entry.

62 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

Android provides several subclasses of Adapter that are useful for retrieving
different kinds of data and building views for an AdapterView ( i.e. ListView
or GridView). The common adapters are ArrayAdapter,Base
Adapter,CursorAdapter, SimpleCursorAdapter,SpinnerAdapter andWr
apperListAdapter.

Android Grid View


Android GridView shows items in two-dimensional scrolling grid (rows &
columns) and the grid items are not necessarily predetermined but they
automatically inserted to the layout using aListAdapter

GRID VIEW
An adapter actually bridges between UI components and the data source that
fill data into UI Component. Adapter can be used to supply the data to like
spinner, list view, grid view etc.

The ListView and GridView are subclasses of AdapterView and they can
be populated by binding them to an Adapter, which retrieves data from an
external source and creates a View that represents each data entry.

63 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

Dialog:-

 A Dialog is Usually a small windows that appears in front of the current activity. The
underlying activity loses focus and the dialog accepts all user interaction dialogs
are normally used for notifications.

 Android supports 4 types dialog boxes:

 AlertDialog : An alert dialog box supports 0 to 3 buttons and a list of selectable


elements, including check boxes and radio buttons. Among the other dialog boxes, the
most suggested dialog box in the alert dialog box.

 In android, AlertDialog is used to prompt a dialog to the user with message


and buttons to perform an action to proceed further.

 The AlertDialog in android application will contain a three regions like as shown below.

 In android Alert Dialogs, we can show a title, up to three buttons, a list of selectable
items or a custom layout based on our requirements.

Region Description

Title It’s an optional and it can be used to show the


detailed messages based on our requirements.

Content It is used to display a message, list or other


Area custom layouts based on our requirements.

64 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

Region Description

Action It is used to display an action buttons to


Buttons interact with the users. We can use upto 3
different action buttons in alert dialog, such as
positive, negative and neutral.

Android AlertDialog Methods


 Following are the some of commonly used methods related to AlertDialog control to
built alert prompt in android applications.

Method Description

setTitle() It is used to set the title of


alertdialog and its an optional
component.

setIcon() It is used to set the icon before the


title

setMessage() It is used to set the message


required message to display in
alertdialog.

setCancelable() It is used to allow users to cancel


alertdialog by clicking on outside of
dialog area by setting true / false.

setPositiveButton() It is used to set the positive button


for alertdialog and we can
implement click event of positive
button.

setNegativeButton() It is used to set the negative button


for alertdialog and we can

65 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

Method Description

implement click event of negative


button.

setNeutralButton() It is used to set the neutral button


for alertdialog and we can
implement click event of neutral
button.

 ProgressDialog : This dialog box displays a progress wheel or progress bar. It is an


extension of AlertDialog and supports adding buttons.

 DatePickerDialog : This dialog box is used for selecting a date by the user.

 TimePickerDialog : This dialog box is used for selecting a time by the user.

66 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

Drawing and Working with Animation :-

 The android framework APIs provides a set 2D drawing APIs that allows
you to render your own graphics onto a canvas or into view.
 It is possible in two ways:
o Draw your graphics or animation into view.
o Draw your graphics directly to canvas.
o Drawables
 Creating from resource images.
 Creating from resource XML.
 Draw Shape.

(1) Draw your graphics or animation into view :

 This is best choice when you want to draw simple graphics that do not
need to change dynamically.
 You should draw the component on view by calling View.onDraw().This
method will be called by the android framework to request that your view
draw itself.

(2) Draw your graphics directly to canvas :

 Drawing to a canvas , is better when our application needs to regularly re-


draw itself.
 Applications such as Video games should be drawing to the canvas on its
own.
 A Canvas works works for you as an interface , to the actual surface upon
which our graphics will be drawn.
 Via the Canvas , our drawing actually performed upon an underlying
bitmap , which is placed into the window.
 However, if you need to create a new canvas ,then you must define the
bitmap upon which drawing will actually be performed.

67 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

 The bitmap is always required for Canvas.


 The Canvas class has its own set of drawing methods that you can use like
, drawBitmap(0 , drawRect(), drawText(), and many more…

(3) Drawables :

 Android offers a custom 2D graphics library for drawing shapes and


images.
 The android.graphics.drawable package contains the common classes for
drawing two dimensions.
 Drawable class extends to define variety of specific classes for drawable
like Bitmampdrawable , Shapedrawable , PictureDrawable ,
LayerDrawable and many more…
 You can use drawable in 3 ways listed above.

Working with Animation

 Android provides a variety of powerful APIs for applying animation to UI


elements.
 It is possible in two ways:
o Tween Animation (View Animation)
o Frame by Frame Animation (Drawable Animation)

(1) Tween Animation :

 We can use view animation system to perform tweened animation on


views.
 Tween animation calculates the animation with information such as the
start point, end point , size , rotation , and other common aspects on an
animation.
 A Tween animation can perform a series of simple transformations (
Position , size , rotation , transparency) on the content of view object.
 So ,if you have any control to move , rotate , grow or shrink the text it is
possible using this animation.
 A sequence of animation defines the tween animation , defined by either
XML or android code.

68 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

 The animation XML file belongs to the res/anim directory of our project.
 The file must have a root element : This will be either a single <alpha > ,
<scale > , <rotate> , <translate> or <set> elements that holds the groups
of these elements.

Example :-

Create New Project

1. Open Android Studio


2. Go to File => New => New Project.
3. Then, select Empty Activity and click on next
 Write application name as DynamicEditTextKotlin
 Select minimum SDK as you need, here we have selected
21 as minimum SDK
 Choose language as Kotlin and click on finish button.

If you have followed above process correctly, you will get a newly created
project successfully.

After creating project we will modify xml files. In xml file we will create
one TextView where all the animations are performed and Eight Buttons for
Eight different animations.

Modify activity_main.xml file

Open res/layout/activity_main.xml file and add code into it.

<?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"
tools:context=".MainActivity">

69 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@+id/linearLayout"
android:gravity="center"
android:text="Geeks for Geeks"
android:textSize="32sp"
android:textColor="@color/colorPrimaryDark"
android:textStyle="bold" />
<LinearLayout
android:id="@+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="2">
<Button
android:id="@+id/fade_in"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="Fade In"

70 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

android:textAllCaps="false" />
<Button
android:id="@+id/fade_out"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="Fade Out"
android:textAllCaps="false" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="2">
<Button
android:id="@+id/zoom_in"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="Zoom In"
android:textAllCaps="false" />
<Button
android:id="@+id/zoom_out"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="Zoom Out"

71 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

android:textAllCaps="false" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="2">
<Button
android:id="@+id/slide_down"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="Slide Down"
android:textAllCaps="false" />
<Button
android:id="@+id/slide_up"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="Slide Up"
android:textAllCaps="false" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="2">

72 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

<Button
android:id="@+id/bounce"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="Bounce"
android:textAllCaps="false" />
<Button
android:id="@+id/rotate"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="Rotate"
android:textAllCaps="false" />
</LinearLayout>
</LinearLayout>
</RelativeLayout>

After modifying the layout we will create xml files for animations. so we will
first create a folder name anim.

In this folder, we will be adding the XML files which will be used to produce
the animations. For this to happen, go to app/res right click and then
select, Android Resource Directory and name it as anim.

bounce.xml

In this animation the text is bounce like a ball.

73 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

<?xml version="1.0" encoding="utf-8"?>


<set
xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/linear_interpolator"
android:fillAfter="true">
<translate
android:fromYDelta="100%"
android:toYDelta="-20%"
android:duration="300" />
<translate
android:startOffset="500"
android:fromYDelta="-20%"
android:toYDelta="10%"
android:duration="150" />
<translate
android:startOffset="1000"
android:fromYDelta="10%"
android:toYDelta="0"
android:duration="100" />
</set>

fade_in.xml

In Fade In animation the text will appear from background.

<?xml version="1.0" encoding="utf-8"?>


<set xmlns:android="http://schemas.android.com/apk/res/android"

74 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

android:interpolator="@android:anim/linear_interpolator">
<alpha
android:duration="1000"
android:fromAlpha="0.1"
android:toAlpha="1.0" />
</set>

fade_out.xml

In Fade Out animation the colour of text is faded for a particular amount of
time.

<?xml version="1.0" encoding="utf-8"?>


<set xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/linear_interpolator">
<alpha
android:duration="1000"
android:fromAlpha="1.0"
android:toAlpha="0.1" />
</set>

rotate.xml

In rotate animation the text is rotated for a particular amount of time.

<?xml version="1.0" encoding="utf-8"?>


<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="1000"

75 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

android:fromDegrees="0"
android:interpolator="@android:anim/linear_interpolator"
android:pivotX="50%"
android:pivotY="50%"
android:startOffset="0"
android:toDegrees="360" />

slide_down.xml

In this animation the text will come from top to bottom.

<?xml version="1.0" encoding="utf-8"?>


<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
android:duration="1000"
android:fromYDelta="-100%"
android:toYDelta="0" />
</set>

slide_up.xml

In this animation the text will go from bottom to top.

<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
android:duration="1000"
android:fromYDelta="0"
android:toYDelta="-100%" />

76 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

</set>

zoom_in.xml

In this animation the text will appear bigger for a particular amount of time.

<?xml version="1.0" encoding="utf-8"?>


<set xmlns:android="http://schemas.android.com/apk/res/android"
android:fillAfter="true">
<scale xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="1000"
android:fromXScale="1"
android:fromYScale="1"
android:pivotX="50%"
android:pivotY="50%"
android:toXScale="1.5"
android:toYScale="1.5">
</scale>
</set>

zoom_out.xml

In this animation the text will appear smaller for a particular amount of time.

<?xml version="1.0" encoding="utf-8"?>


<set xmlns:android="http://schemas.android.com/apk/res/android"
android:fillAfter="true" >
<scale

77 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="1000"
android:fromXScale="1.0"
android:fromYScale="1.0"
android:pivotX="50%"
android:pivotY="50%"
android:toXScale="0.5"
android:toYScale="0.5" >
</scale>
</set>

Create MainActivity.kt file

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.view.View
import android.view.animation.AnimationUtils
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {


override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
fade_in.setOnClickListener {

78 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

textView.visibility = View.VISIBLE
val animationFadeIn = AnimationUtils.loadAnimation(this, R.anim.fade_in)
textView.startAnimation(animationFadeIn)
}
fade_out.setOnClickListener {
val animationFadeOut = AnimationUtils.loadAnimation(this, R.anim.fade_out)
textView.startAnimation(animationFadeOut)
Handler().postDelayed({
textView.visibility = View.GONE
}, 1000)
}
zoom_in.setOnClickListener {
val animationZoomIn = AnimationUtils.loadAnimation(this, R.anim.zoom_in)
textView.startAnimation(animationZoomIn)
}
zoom_out.setOnClickListener {
val animationZoomOut = AnimationUtils.loadAnimation(this,
R.anim.zoom_out)
textView.startAnimation(animationZoomOut)
}
slide_down.setOnClickListener {
val animationSlideDown = AnimationUtils.loadAnimation(this, R.anim.slide_in)
textView.startAnimation(animationSlideDown)
}
slide_up.setOnClickListener {

79 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

val animationSlideUp = AnimationUtils.loadAnimation(this, R.anim.slide_out)


textView.startAnimation(animationSlideUp)
}
bounce.setOnClickListener {
val animationBounce = AnimationUtils.loadAnimation(this, R.anim.bounce)
textView.startAnimation(animationBounce)
}
rotate.setOnClickListener {
val animationRotate = AnimationUtils.loadAnimation(this, R.anim.rotate)
textView.startAnimation(animationRotate)
}
}
}

AndroidManifest.xml file

Code inside src/main/AndroidManifest.xml file would look like below

<?xml version="1.0" encoding="utf-8"?>


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="net.geeksforgeeks.animationsinkotlin">

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"

80 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />


</intent-filter>
</activity>
</application>

</manifest>

(2) Frame by Frame Animation :

 Frame by Frame animation or Drawable animation let you load a series of


drawable resources one after another to create an animation.
 This is traditional animation sense that it is created with a sequence of
different images, played in an order.
 While we define the frames of animation in our code , using the
AnimationDrawable class with single XML file.
 The XML file for this kind of animation belongs in the res/drawable
directory of our android project.
 The XML file consistes of an <animation-list> element as the root node
and a series of child <item> nodes that each defines a frame : Frame
duration and a drawable resource.

<?xml version="1.0" encoding="utf-8"?>


<animation-list

81 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

xmlns:android="http://schemas.android.com/apk/res/android"
android:oneshot="false">

<item
android:duration="100"
android:drawable="@mipmap/robot_start_1"/>

<item
android:duration="100"
android:drawable="@mipmap/robot_start_2"/>

<item
android:duration="100"
android:drawable="@mipmap/robot_start_3"/>[etc...the
sample app has about 40 frames]
</animation-list>

The final Kotlin code is as follows:

package robkerr.com.robotwalker

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.graphics.drawable.AnimationDrawable
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

startWalking.setOnClickListener {
val bgImage = imageView.background as
AnimationDrawable
bgImage.start()
}

stopWalking.setOnClickListener {
val bgImage = imageView.background as
AnimationDrawable
bgImage.stop()
}
}
}

82 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

83 | P a g e
Prepared By : Bhartiba Parmar

You might also like