Android Widgets
There are many widgets in android example – Button, EditText,
AutoCompleteTextView, ToggleButton, DatePicker etc. These widgets are easy to
learn. The widgets with examples are given below:
Android Button
Android buttons are push buttons. The android.widget.Button is subclass of
TextView class and CompoundButton is the subclass of Button class. Various
buttons are there like – RadioButton, ToggleButton, CompoundButton etc.
CompoundButton -> Button -> TextView -> View -> Object
Example
xml 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=”.MainActivity”
android:background=”@color/teal_700″>
<EditText
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:layout_marginLeft=”20dp”
android:layout_marginRight=”20dp”
android:layout_marginTop=”40dp”
android:hint=”@string/name”
android:textSize=”25sp”
android:padding=”20dp”
android:id=”@+id/nameET”
android:background=”@drawable/round” />
<EditText
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:layout_marginLeft=”20dp”
android:layout_marginRight=”20dp”
android:layout_marginTop=”15dp”
android:hint=”@string/email”
android:textSize=”25sp”
android:padding=”20dp”
android:layout_below=”@+id/nameET”
android:id=”@+id/emailET”
android:background=”@drawable/round” />
<Button
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Go”
android:textSize=”30sp”
android:layout_below=”@id/emailET”
android:layout_marginTop=”20dp”
android:layout_centerHorizontal=”true”
android:backgroundTint=”@color/teal_200″
android:id=”@+id/goBtn”/>
</RelativeLayout>
Java code
package com.example.notescode
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
class MainActivity : AppCompatActivity() {
private lateinit var goBtn:Button
private lateinit var nameET:EditText
private lateinit var emailET:EditText
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setClicks()
}
private fun setClicks() {
elementsBinding()
goBtn.setOnClickListener(View.OnClickListener {
// Code for task when button click
Toast.makeText(applicationContext, “Hello”, Toast.LENGTH_LONG).show()
})
}
private fun elementsBinding() {
goBtn = findViewById(R.id.goBtn)
nameET = findViewById(R.id.nameET)
emailET = findViewById(R.id.emailET)
}
}
Output
How to make corners round?
First you have to make a xml file and write the following code inside that file than
add that file in the background tag of that element which you want to make round.
Code
<?xml version=”1.0″ encoding=”utf-8″?>
<shape xmlns:android=”http://schemas.android.com/apk/res/android”>
<corners android:radius=”25dp”/>
<solid android:color=”@color/white”/>
</shape>
Android Toast
Toast are used to show information for short or long time. The android.widget.Toast
class is the subclass of java.lang.Object class.
Toast -> Object
Toast class
public static final int LENGTH_LONG – display view for long period of
time
public static final int LENGTH_SHORT – display view for short period
of time
public static Toast makeText(Context context, CharSequence text,
int duration) – makes the toast containing text and duration
public void show() – show toast
public void setMargin (float horizontalMargin, float
verticalMargin) – changes the horizontal and vertical margin difference.
Example
xml 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=”.MainActivity”
android:background=”@color/teal_700″>
<EditText
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:layout_marginLeft=”20dp”
android:layout_marginRight=”20dp”
android:layout_marginTop=”40dp”
android:hint=”@string/name”
android:textSize=”25sp”
android:padding=”20dp”
android:id=”@+id/nameET”
android:background=”@drawable/round” />
<EditText
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:layout_marginLeft=”20dp”
android:layout_marginRight=”20dp”
android:layout_marginTop=”15dp”
android:hint=”@string/email”
android:textSize=”25sp”
android:padding=”20dp”
android:layout_below=”@+id/nameET”
android:id=”@+id/emailET”
android:background=”@drawable/round” />
<Button
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Go”
android:textSize=”30sp”
android:layout_below=”@id/emailET”
android:layout_marginTop=”20dp”
android:layout_centerHorizontal=”true”
android:backgroundTint=”@color/teal_200″
android:id=”@+id/goBtn”/>
</RelativeLayout>
Java code
package com.example.notescode
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
class MainActivity : AppCompatActivity() {
private lateinit var goBtn:Button
private lateinit var nameET:EditText
private lateinit var emailET:EditText
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setClicks()
}
private fun setClicks() {
elementsBinding()
goBtn.setOnClickListener(View.OnClickListener {
// Code for task when button click
Toast.makeText(applicationContext, “Hello”, Toast.LENGTH_LONG).show()
})
}
private fun elementsBinding() {
goBtn = findViewById(R.id.goBtn)
nameET = findViewById(R.id.nameET)
emailET = findViewById(R.id.emailET)
}
}
Output
Custom toast
We can also create custom toast in android. We can add icon change width and
length etc.
For this we have to create another layout file and add that file in toast object.
Example
customtoast.xml
<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:id=”@+id/custom_toast_layout”
android:orientation=”vertical”
android:background=”@color/teal_200″
>
<ImageView
android:id=”@+id/custom_toast_image”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:contentDescription=”Hello world”
android:src=”@drawable/ic_launcher_background”/>
<TextView
android:id=”@+id/custom_toast_message”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:contentDescription=”To”
android:text=”@string/custom_toast”
android:textSize=”20sp”
android:textColor=”@color/white”/>
</LinearLayout>
mainxml
<?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=”.MainActivity”
android:background=”@color/teal_700″>
<EditText
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:layout_marginLeft=”20dp”
android:layout_marginRight=”20dp”
android:layout_marginTop=”40dp”
android:hint=”@string/name”
android:textSize=”25sp”
android:padding=”20dp”
android:id=”@+id/nameET”
android:background=”@drawable/round” />
<EditText
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:layout_marginLeft=”20dp”
android:layout_marginRight=”20dp”
android:layout_marginTop=”15dp”
android:hint=”@string/email”
android:textSize=”25sp”
android:padding=”20dp”
android:layout_below=”@+id/nameET”
android:id=”@+id/emailET”
android:background=”@drawable/round” />
<Button
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Go”
android:textSize=”30sp”
android:layout_below=”@id/emailET”
android:layout_marginTop=”20dp”
android:layout_centerHorizontal=”true”
android:backgroundTint=”@color/teal_200″
android:id=”@+id/goBtn”/>
</RelativeLayout>
Java code
package com.example.notescode
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
class MainActivity : AppCompatActivity() {
private lateinit var goBtn:Button
private lateinit var nameET:EditText
private lateinit var emailET:EditText
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setClicks()
}
private fun setClicks() {
elementsBinding()
goBtn.setOnClickListener(View.OnClickListener {
// Code for task when button click
var li:LayoutInflater = layoutInflater
var layout:View = li.inflate(R.layout.customtoast,
findViewById(R.id.custom_toast_layout))
var tost:Toast = Toast(applicationContext)
tost.duration = Toast.LENGTH_LONG
tost.view = layout
tost.show()
})
}
private fun elementsBinding() {
goBtn = findViewById(R.id.goBtn)
nameET = findViewById(R.id.nameET)
emailET = findViewById(R.id.emailET)
}
}
Output
ToggleButton and CheckBox
ToggleButton – It is on/off button in android. It is used to display check and
uncheck. Android ToggleButton and Switch both are the subclasses of
CompoundButton class.
ToggleButton -> CompoundButton -> Button -> TextView -> View -> Object
ToggleButton XML attribute
android:disableAlpha – The alpha to apply to the indicator when disabled.
android:textOff – Text for the button when it is not checked
android:textOn – Text for the button when it is checked
Methods
CharSequence getTextOff() – Returns the text when button is not in the
checked state.
CharSequence getTextOn() – Returns the text when button is in the
checked state.
void setChecked(boolean checked) – Changes the checked state of this
button.
CheckBox – It has two states. It is either checked or unchecked. Android CheckBox
class is the subclass of CompoundButton class.
CheckBox -> CompoundButton -> Button -> TextView -> View -> Object
Methods of CheckBox class
public boolean isChecked() – Returns true if it is checked otherwise false.
public void setChecked(boolean status) – Changes the state of the
CheckBox.
Example
xml 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=”.MainActivity”
android:background=”@color/teal_700″>
<EditText
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:layout_marginLeft=”20dp”
android:layout_marginRight=”20dp”
android:layout_marginTop=”40dp”
android:hint=”@string/name”
android:textSize=”25sp”
android:padding=”20dp”
android:id=”@+id/nameET”
android:background=”@drawable/round” />
<EditText
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:layout_marginLeft=”20dp”
android:layout_marginRight=”20dp”
android:layout_marginTop=”15dp”
android:hint=”@string/email”
android:textSize=”25sp”
android:padding=”20dp”
android:layout_below=”@+id/nameET”
android:id=”@+id/emailET”
android:background=”@drawable/round” />
<LinearLayout
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_centerHorizontal=”true”
android:id=”@+id/layoutForToggle”
android:orientation=”horizontal”
android:layout_below=”@id/emailET”>
<TextView
android:id=”@+id/textForToggle”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_marginTop=”20dp”
android:textSize=”25sp”
android:textColor=”@color/white”
android:textStyle=”bold”
android:layout_marginRight=”20dp”
android:text=”@string/employed_or_not” />
<ToggleButton
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:id=”@+id/employedOrNot”
android:layout_marginTop=”20dp”
android:textColor=”@color/white”
android:textSize=”20sp”
android:textOff=”@string/no”
android:textOn=”@string/yes”
android:background=”@color/teal_200″/>
</LinearLayout>
<LinearLayout
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_centerHorizontal=”true”
android:id=”@+id/layoutForGender”
android:orientation=”horizontal”
android:layout_below=”@id/layoutForToggle”>
<TextView
android:id=”@+id/textForGender”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_marginTop=”20dp”
android:textSize=”25sp”
android:textColor=”@color/white”
android:textStyle=”bold”
android:layout_marginRight=”20dp”
android:text=”@string/gender” />
<CheckBox
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:id=”@+id/genderMale”
android:layout_marginTop=”20dp”
android:textColor=”@color/white”
android:textSize=”20sp”
android:text=”@string/male”
android:paddingRight=”20dp”
android:background=”@color/teal_200″/>
<CheckBox
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:id=”@+id/genderFemale”
android:layout_marginTop=”20dp”
android:textColor=”@color/white”
android:textSize=”20sp”
android:text=”@string/female”
android:paddingRight=”20dp”
android:layout_marginLeft=”10dp”
android:background=”@color/teal_200″/>
</LinearLayout>
<androidx.appcompat.widget.AppCompatButton
android:layout_width=”100dp”
android:layout_height=”100dp”
android:text=”@string/go”
android:textSize=”30sp”
android:layout_below=”@id/layoutForGender”
android:layout_marginTop=”50dp”
android:background=”@drawable/round”
android:layout_centerHorizontal=”true”
android:backgroundTint=”@color/teal_200″
android:id=”@+id/goBtn”
android:textColor=”@color/white”
android:textStyle=”bold”/>
<TextView
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_centerHorizontal=”true”
android:layout_marginTop=”50dp”
android:id=”@+id/result”
android:layout_below=”@id/goBtn”/>
</RelativeLayout>
Java code
package com.example.notescode
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.*
class MainActivity : AppCompatActivity() {
private lateinit var goBtn:Button
private lateinit var nameET:EditText
private lateinit var emailET:EditText
private lateinit var employedToggle:ToggleButton
private lateinit var genderMale:CheckBox
private lateinit var genderFemale:CheckBox
private lateinit var result:TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setClicks()
}
private fun setClicks() {
elementsBinding()
goBtn.setOnClickListener(View.OnClickListener {
// Code for task when button click
val name = nameET.text.toString()
val email = emailET.text.toString()
val employed = if(employedToggle.isChecked){
“Yes”
} else{
“No”
}
val gender = if(genderMale.isChecked){
“Male”
} else{
“female”
}
result.text = “Hello $name\nYour email is $email\nEmployed:
$employed\nGender: $gender”
})
}
private fun elementsBinding() {
goBtn = findViewById(R.id.goBtn)
nameET = findViewById(R.id.nameET)
emailET = findViewById(R.id.emailET)
employedToggle = findViewById(R.id.employedOrNot)
genderMale = findViewById(R.id.genderMale)
genderFemale = findViewById(R.id.genderFemale)
result = findViewById(R.id.result)
}
}
Output –
When you click on button than the info entered by you will be shown in the textView
Alert dialog
This is used to display a alert message with ok and cancel button. Android
AlertDialog is composed of three regions: title, content area and action buttons.
Android AlertDialog is the subclass of Dialog class.
AlertDialog -> Dialog ->Object
Methods
public AlertDialog.Builder setTitle(CharSequence) – This method is
used to set the title of AlertDialog.
public AlertDialog.Builder setMessage(CharSequence) – This method
is used to set the message for AlertDialog.
public AlertDialog.Builder setIcon(int) – This method is used to set the
icon over AlertDialog.
Example
xml 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=”.MainActivity”
android:background=”@color/teal_700″>
<EditText
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:layout_marginLeft=”20dp”
android:layout_marginRight=”20dp”
android:layout_marginTop=”40dp”
android:hint=”@string/name”
android:textSize=”25sp”
android:padding=”20dp”
android:id=”@+id/nameET”
android:background=”@drawable/round” />
<EditText
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:layout_marginLeft=”20dp”
android:layout_marginRight=”20dp”
android:layout_marginTop=”15dp”
android:hint=”@string/email”
android:textSize=”25sp”
android:padding=”20dp”
android:layout_below=”@+id/nameET”
android:id=”@+id/emailET”
android:background=”@drawable/round” />
<LinearLayout
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_centerHorizontal=”true”
android:id=”@+id/layoutForToggle”
android:orientation=”horizontal”
android:layout_below=”@id/emailET”>
<TextView
android:id=”@+id/textForToggle”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_marginTop=”20dp”
android:textSize=”25sp”
android:textColor=”@color/white”
android:textStyle=”bold”
android:layout_marginRight=”20dp”
android:text=”@string/employed_or_not” />
<ToggleButton
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:id=”@+id/employedOrNot”
android:layout_marginTop=”20dp”
android:textColor=”@color/white”
android:textSize=”20sp”
android:textOff=”@string/no”
android:textOn=”@string/yes”
android:background=”@color/teal_200″/>
</LinearLayout>
<LinearLayout
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_centerHorizontal=”true”
android:id=”@+id/layoutForGender”
android:orientation=”horizontal”
android:layout_below=”@id/layoutForToggle”>
<TextView
android:id=”@+id/textForGender”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_marginTop=”20dp”
android:textSize=”25sp”
android:textColor=”@color/white”
android:textStyle=”bold”
android:layout_marginRight=”20dp”
android:text=”@string/gender” />
<CheckBox
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:id=”@+id/genderMale”
android:layout_marginTop=”20dp”
android:textColor=”@color/white”
android:textSize=”20sp”
android:text=”@string/male”
android:paddingRight=”20dp”
android:background=”@color/teal_200″/>
<CheckBox
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:id=”@+id/genderFemale”
android:layout_marginTop=”20dp”
android:textColor=”@color/white”
android:textSize=”20sp”
android:text=”@string/female”
android:paddingRight=”20dp”
android:layout_marginLeft=”10dp”
android:background=”@color/teal_200″/>
</LinearLayout>
<androidx.appcompat.widget.AppCompatButton
android:layout_width=”100dp”
android:layout_height=”100dp”
android:text=”@string/go”
android:textSize=”30sp”
android:layout_below=”@id/layoutForGender”
android:layout_marginTop=”50dp”
android:background=”@drawable/round”
android:layout_centerHorizontal=”true”
android:backgroundTint=”@color/teal_200″
android:id=”@+id/goBtn”
android:textColor=”@color/white”
android:textStyle=”bold”/>
<TextView
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_centerHorizontal=”true”
android:layout_marginTop=”50dp”
android:id=”@+id/result”
android:layout_below=”@id/goBtn”/>
</RelativeLayout>
Java code
package com.example.notescode
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.*
import androidx.appcompat.app.AlertDialog
class MainActivity : AppCompatActivity() {
private lateinit var goBtn:Button
private lateinit var nameET:EditText
private lateinit var emailET:EditText
private lateinit var employedToggle:ToggleButton
private lateinit var genderMale:CheckBox
private lateinit var genderFemale:CheckBox
private lateinit var result:TextView
private lateinit var dialogAlert:AlertDialog.Builder
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setClicks()
}
private fun setClicks() {
elementsBinding()
goBtn.setOnClickListener(View.OnClickListener {
// Code for task when button click
if(nameET.text.isEmpty()){
dialogAlert.setMessage(“Name field is empty”).setCancelable(true)
val alert:AlertDialog = dialogAlert.create()
alert.setTitle(“Warning!”)
alert.show()
}
else if(emailET.text.isEmpty()){
dialogAlert.setMessage(“Email field is empty”).setCancelable(true)
val alert:AlertDialog = dialogAlert.create()
alert.setTitle(“Warning!”)
alert.show()
}
else{
val name = nameET.text.toString()
val email = emailET.text.toString()
val employed = if(employedToggle.isChecked){
“Yes”
} else{
“No”
}
val gender = if(genderMale.isChecked){
“Male”
} else{
“female”
}
result.text = “Hello $name\nYour email is $email\nEmployed:
$employed\nGender: $gender”
}
})
}
private fun elementsBinding() {
goBtn = findViewById(R.id.goBtn)
nameET = findViewById(R.id.nameET)
emailET = findViewById(R.id.emailET)
employedToggle = findViewById(R.id.employedOrNot)
genderMale = findViewById(R.id.genderMale)
genderFemale = findViewById(R.id.genderFemale)
result = findViewById(R.id.result)
dialogAlert = AlertDialog.Builder(this)
}
}
Output-
Spinner
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.
Spinner -> AbsSpinner -> AdapterView -> ViewGroup -> View -> Object
Example
Java code
package com.example.notescode
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.*
import androidx.appcompat.app.AlertDialog
class MainActivity : AppCompatActivity() , AdapterView.OnItemSelectedListener{
private lateinit var goBtn:Button
private lateinit var nameET:EditText
private lateinit var emailET:EditText
private lateinit var employedToggle:ToggleButton
private lateinit var genderMale:CheckBox
private lateinit var genderFemale:CheckBox
private lateinit var result:TextView
private lateinit var dialogAlert:AlertDialog.Builder
private lateinit var spin:Spinner
private val countries = arrayListOf<String>(“”,”India”, “USA”, “Japan”, “China”)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
elementsBinding()
spin.onItemSelectedListener
val aa = ArrayAdapter(applicationContext,
com.google.android.material.R.layout.support_simple_spinner_dropdown_item,
countries)
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spin.adapter = aa
clickButtons()
}
private fun clickButtons() {
goBtn.setOnClickListener(View.OnClickListener {
if(nameET.text.isEmpty()){
dialogAlert.setMessage(“Name field is empty”).setCancelable(true)
val alert:AlertDialog = dialogAlert.create()
alert.setTitle(“Warning!”)
alert.show()
}
else if(emailET.text.isEmpty()){
dialogAlert.setMessage(“Email field is empty”).setCancelable(true)
val alert:AlertDialog = dialogAlert.create()
alert.setTitle(“Warning!”)
alert.show()
}
else if(spin.selectedItem.toString()==””){
dialogAlert.setMessage(“Please select country”).setCancelable(true)
val alert:AlertDialog = dialogAlert.create()
alert.setTitle(“Warning!”)
alert.show()
}
else{
val name = nameET.text.toString()
val email = emailET.text.toString()
val employed = if(employedToggle.isChecked){
“Yes”
} else{
“No”
}
val gender = if(genderMale.isChecked){
“Male”
} else{
“female”
}
val country = spin.selectedItem.toString()
result.text = “Hello $name\nYour email is $email\nEmployed:
$employed\nGender: $gender\nYour country is: $country”
}
})
}
private fun elementsBinding() {
goBtn = findViewById(R.id.goBtn)
nameET = findViewById(R.id.nameET)
emailET = findViewById(R.id.emailET)
employedToggle = findViewById(R.id.employedOrNot)
genderMale = findViewById(R.id.genderMale)
genderFemale = findViewById(R.id.genderFemale)
result = findViewById(R.id.result)
dialogAlert = AlertDialog.Builder(this)
spin = findViewById(R.id.countriesSpinner)
}
override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
TODO(“Not yet implemented”)
}
override fun onNothingSelected(p0: AdapterView<*>?) {
TODO(“Not yet implemented”)
}
}
xml 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=”.MainActivity”
android:background=”@color/teal_700″>
<EditText
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:layout_marginLeft=”20dp”
android:layout_marginRight=”20dp”
android:layout_marginTop=”40dp”
android:hint=”@string/name”
android:textSize=”25sp”
android:padding=”20dp”
android:id=”@+id/nameET”
android:background=”@drawable/round” />
<EditText
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:layout_marginLeft=”20dp”
android:layout_marginRight=”20dp”
android:layout_marginTop=”15dp”
android:hint=”@string/email”
android:textSize=”25sp”
android:padding=”20dp”
android:layout_below=”@+id/nameET”
android:id=”@+id/emailET”
android:background=”@drawable/round” />
<LinearLayout
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_centerHorizontal=”true”
android:id=”@+id/layoutForToggle”
android:orientation=”horizontal”
android:layout_below=”@id/emailET”>
<TextView
android:id=”@+id/textForToggle”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_marginTop=”20dp”
android:textSize=”25sp”
android:textColor=”@color/white”
android:textStyle=”bold”
android:layout_marginRight=”20dp”
android:text=”@string/employed_or_not” />
<ToggleButton
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:id=”@+id/employedOrNot”
android:layout_marginTop=”20dp”
android:textColor=”@color/white”
android:textSize=”20sp”
android:textOff=”@string/no”
android:textOn=”@string/yes”
android:background=”@color/teal_200″/>
</LinearLayout>
<LinearLayout
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_centerHorizontal=”true”
android:id=”@+id/layoutForGender”
android:orientation=”horizontal”
android:layout_below=”@id/layoutForToggle”>
<TextView
android:id=”@+id/textForGender”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_marginTop=”20dp”
android:textSize=”25sp”
android:textColor=”@color/white”
android:textStyle=”bold”
android:layout_marginRight=”20dp”
android:text=”@string/gender” />
<CheckBox
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:id=”@+id/genderMale”
android:layout_marginTop=”20dp”
android:textColor=”@color/white”
android:textSize=”20sp”
android:text=”@string/male”
android:paddingRight=”20dp”
android:background=”@color/teal_200″/>
<CheckBox
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:id=”@+id/genderFemale”
android:layout_marginTop=”20dp”
android:textColor=”@color/white”
android:textSize=”20sp”
android:text=”@string/female”
android:paddingRight=”20dp”
android:layout_marginLeft=”10dp”
android:background=”@color/teal_200″/>
</LinearLayout>
<Spinner
android:id=”@+id/countriesSpinner”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_below=”@id/layoutForGender”
android:layout_marginTop=”50dp”
android:layout_centerHorizontal=”true” />
<androidx.appcompat.widget.AppCompatButton
android:layout_width=”100dp”
android:layout_height=”100dp”
android:text=”@string/go”
android:textSize=”30sp”
android:layout_below=”@id/countriesSpinner”
android:layout_marginTop=”50dp”
android:background=”@drawable/round”
android:layout_centerHorizontal=”true”
android:backgroundTint=”@color/teal_200″
android:id=”@+id/goBtn”
android:textColor=”@color/white”
android:textStyle=”bold”/>
<TextView
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_centerHorizontal=”true”
android:layout_marginTop=”50dp”
android:id=”@+id/result”
android:layout_below=”@id/goBtn”/>
</RelativeLayout>
Output
AutoComplete TextView
Using AutoComplete TextView we can show hint based on the characters entered by
the user to the user. Android AutoCompleteTextView is a editable text field, it
displays a list of suggestions in a drop down menu from which user can select only
one suggestion or value.
MultiAutoComplete TextView -> AutoComplete TextView -> EditText -> TextView –
> View -> Object
RatingBar
It is used to get ratting from the user. It can be 2.0, 2.1, 2.3, 5, etc. Android
RatingBar displays the rating in stars. Android RatingBar is the subclass of
AbsSeekBar class.
getRating() method is used to get rating number.
RatingBar –> AbsSeekBAr -> ProgressBar -> View -> Object
Example
xml 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=”.MainActivity”
android:background=”@color/teal_700″>
<EditText
android:id=”@+id/nameET”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:layout_marginLeft=”20dp”
android:layout_marginTop=”40dp”
android:layout_marginRight=”20dp”
android:background=”@drawable/round”
android:hint=”@string/name”
android:padding=”20dp”
android:textSize=”25sp” />
<AutoCompleteTextView
android:id=”@+id/autoCompleteTextView”
android:layout_width=”200dp”
android:layout_height=”wrap_content”
android:layout_centerHorizontal=”true”
android:text=””
android:layout_below=”@+id/nameET” />
<EditText
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:layout_marginLeft=”20dp”
android:layout_marginRight=”20dp”
android:layout_marginTop=”15dp”
android:hint=”@string/email”
android:textSize=”25sp”
android:padding=”20dp”
android:layout_below=”@+id/nameET”
android:id=”@+id/emailET”
android:background=”@drawable/round” />
<LinearLayout
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_centerHorizontal=”true”
android:id=”@+id/layoutForToggle”
android:orientation=”horizontal”
android:layout_below=”@id/emailET”>
<TextView
android:id=”@+id/textForToggle”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_marginTop=”20dp”
android:textSize=”25sp”
android:textColor=”@color/white”
android:textStyle=”bold”
android:layout_marginRight=”20dp”
android:text=”@string/employed_or_not” />
<ToggleButton
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:id=”@+id/employedOrNot”
android:layout_marginTop=”20dp”
android:textColor=”@color/white”
android:textSize=”20sp”
android:textOff=”@string/no”
android:textOn=”@string/yes”
android:background=”@color/teal_200″/>
</LinearLayout>
<LinearLayout
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_centerHorizontal=”true”
android:id=”@+id/layoutForGender”
android:orientation=”horizontal”
android:layout_below=”@id/layoutForToggle”>
<TextView
android:id=”@+id/textForGender”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_marginTop=”20dp”
android:textSize=”25sp”
android:textColor=”@color/white”
android:textStyle=”bold”
android:layout_marginRight=”20dp”
android:text=”@string/gender” />
<CheckBox
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:id=”@+id/genderMale”
android:layout_marginTop=”20dp”
android:textColor=”@color/white”
android:textSize=”20sp”
android:text=”@string/male”
android:paddingRight=”20dp”
android:background=”@color/teal_200″/>
<CheckBox
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:id=”@+id/genderFemale”
android:layout_marginTop=”20dp”
android:textColor=”@color/white”
android:textSize=”20sp”
android:text=”@string/female”
android:paddingRight=”20dp”
android:layout_marginLeft=”10dp”
android:background=”@color/teal_200″/>
</LinearLayout>
<Spinner
android:id=”@+id/countriesSpinner”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_below=”@id/layoutForGender”
android:layout_centerHorizontal=”true”
android:layout_marginTop=”20dp” />
<androidx.appcompat.widget.AppCompatButton
android:layout_width=”100dp”
android:layout_height=”100dp”
android:text=”@string/go”
android:textSize=”30sp”
android:layout_below=”@id/countriesSpinner”
android:layout_marginTop=”20dp”
android:background=”@drawable/round”
android:layout_centerHorizontal=”true”
android:backgroundTint=”@color/teal_200″
android:id=”@+id/goBtn”
android:textColor=”@color/white”
android:textStyle=”bold”/>
<RatingBar
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_below=”@id/goBtn”
android:layout_marginTop=”20dp”
android:id=”@+id/ratingApp”
android:layout_centerHorizontal=”true”/>
<TextView
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_centerHorizontal=”true”
android:layout_marginTop=”50dp”
android:id=”@+id/result”
android:layout_below=”@id/ratingApp” />
</RelativeLayout>
Java code
package com.example.notescode
import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.widget.*
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() , AdapterView.OnItemSelectedListener{
private lateinit var goBtn:Button
private lateinit var nameET:EditText
private lateinit var emailET:EditText
private lateinit var employedToggle:ToggleButton
private lateinit var genderMale:CheckBox
private lateinit var genderFemale:CheckBox
private lateinit var result:TextView
private lateinit var dialogAlert:AlertDialog.Builder
private lateinit var spin:Spinner
private lateinit var autoCTV:AutoCompleteTextView
private lateinit var ratingBarForRating:RatingBar
private val countries = arrayListOf<String>(“”,”India”, “USA”, “Japan”, “China”)
// ———> Spinner
var names = arrayOf(“Abhi”, “Abhishek”, “Abhishek Bansal”, “Bansal”, “Harsh”,
“Aman”, “Sumit”, “Siddant”) // ———> AutoComplete
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
elementsBinding()
spin.onItemSelectedListener
val aa = ArrayAdapter(applicationContext,
com.google.android.material.R.layout.support_simple_spinner_dropdown_item,
countries)
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spin.adapter = aa
val auto_Complete_Adapter: ArrayAdapter<String> =
ArrayAdapter<String>(this, android.R.layout.select_dialog_item, names)
autoCTV.threshold = 1
autoCTV.setAdapter(auto_Complete_Adapter)
autoCTV.setTextColor(Color.YELLOW)
clickButtons()
}
private fun clickButtons() {
goBtn.setOnClickListener(View.OnClickListener {
if(nameET.text.isEmpty()){
dialogAlert.setMessage(“Name field is empty”).setCancelable(true)
val alert:AlertDialog = dialogAlert.create()
alert.setTitle(“Warning!”)
alert.show()
}
else if(emailET.text.isEmpty()){
dialogAlert.setMessage(“Email field is empty”).setCancelable(true)
val alert:AlertDialog = dialogAlert.create()
alert.setTitle(“Warning!”)
alert.show()
}
else if(spin.selectedItem.toString()==””){
dialogAlert.setMessage(“Please select country”).setCancelable(true)
val alert:AlertDialog = dialogAlert.create()
alert.setTitle(“Warning!”)
alert.show()
}
else{
val name = nameET.text.toString()
val email = emailET.text.toString()
val employed = if(employedToggle.isChecked){
“Yes”
} else{
“No”
}
val gender = if(genderMale.isChecked){
“Male”
} else{
“female”
}
val country = spin.selectedItem.toString()
val rating: String = java.lang.String.valueOf(ratingBarForRating.rating)
Toast.makeText(this, “You give $rating start rating to this app!”,
Toast.LENGTH_LONG).show()
result.text = “Hello $name\nYour email is $email\nEmployed:
$employed\nGender: $gender\nYour country is: $country”
}
})
}
private fun elementsBinding() {
goBtn = findViewById(R.id.goBtn)
nameET = findViewById(R.id.nameET)
emailET = findViewById(R.id.emailET)
employedToggle = findViewById(R.id.employedOrNot)
genderMale = findViewById(R.id.genderMale)
genderFemale = findViewById(R.id.genderFemale)
result = findViewById(R.id.result)
dialogAlert = AlertDialog.Builder(this)
spin = findViewById(R.id.countriesSpinner)
autoCTV = findViewById(R.id.autoCompleteTextView)
ratingBarForRating = findViewById(R.id.ratingApp)
}
override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
TODO(“Not yet implemented”)
}
override fun onNothingSelected(p0: AdapterView<*>?) {
TODO(“Not yet implemented”)
}
}
Output
DatePicker
It is used to select date. It is used to select date by say, month, year.
DatePicker -> FrameLayout -> Viewgroup -> View -> Object
Example
xml 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=”.MainActivity3″>
<ScrollView
android:layout_width=”match_parent”
android:layout_height=”match_parent”>
<LinearLayout
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:orientation=”vertical”
android:gravity=”center”>
<TimePicker
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_marginTop=”20dp”
android:id=”@+id/timePicker”
android:layout_marginLeft=”30dp”
android:layout_marginRight=”30dp”/>
<DatePicker
android:id=”@+id/datePicker”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_marginTop=”20dp” />
<Button
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Show Date and Time”
android:id=”@+id/showBtn”
android:layout_marginTop=”20dp” />
</LinearLayout>
</ScrollView>
</RelativeLayout>
Java code
package com.example.notescode
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.DatePicker
import android.widget.TimePicker
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class MainActivity3 : AppCompatActivity() {
private lateinit var picker:DatePicker
private lateinit var timepicker:TimePicker
private lateinit var showBtn:Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main3)
picker = findViewById(R.id.datePicker)
timepicker = findViewById(R.id.timePicker)
showBtn = findViewById(R.id.showBtn)
val date = getDate()
val time = getTime()
showBtn.setOnClickListener(View.OnClickListener {
Toast.makeText(applicationContext, “Selected date is: $date\nSelected time
is: $time”, Toast.LENGTH_LONG).show()
})
}
private fun getDate(): String? {
val builder = StringBuilder()
builder.append((picker.month + 1).toString() + “/”)
builder.append(picker.dayOfMonth.toString() + “/”)
builder.append(picker.year)
return builder.toString()
}
private fun getTime(): String? {
return “Current Time: ” + timepicker.currentHour.toString() + “:” +
timepicker.currentMinute.toString()
}
}
Output
TimePicker
Like DatePicker android also provide TimePicker. It allows you to select time. You
cannot select time by seconds.
TimePicker -> frameLayout -> ViewGroup -> View -> Object
Example
xml 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=”.MainActivity3″>
<ScrollView
android:layout_width=”match_parent”
android:layout_height=”match_parent”>
<LinearLayout
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:orientation=”vertical”
android:gravity=”center”>
<TimePicker
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_marginTop=”20dp”
android:id=”@+id/timePicker”
android:layout_marginLeft=”30dp”
android:layout_marginRight=”30dp”/>
<DatePicker
android:id=”@+id/datePicker”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_marginTop=”20dp” />
<Button
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Show Date and Time”
android:id=”@+id/showBtn”
android:layout_marginTop=”20dp” />
</LinearLayout>
</ScrollView>
</RelativeLayout>
Java code
package com.example.notescode
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.DatePicker
import android.widget.TimePicker
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class MainActivity3 : AppCompatActivity() {
private lateinit var picker:DatePicker
private lateinit var timepicker:TimePicker
private lateinit var showBtn:Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main3)
picker = findViewById(R.id.datePicker)
timepicker = findViewById(R.id.timePicker)
showBtn = findViewById(R.id.showBtn)
val date = getDate()
val time = getTime()
showBtn.setOnClickListener(View.OnClickListener {
Toast.makeText(applicationContext, “Selected date is: $date\nSelected time
is: $time”, Toast.LENGTH_LONG).show()
})
}
private fun getDate(): String? {
val builder = StringBuilder()
builder.append((picker.month + 1).toString() + “/”)
builder.append(picker.dayOfMonth.toString() + “/”)
builder.append(picker.year)
return builder.toString()
}
private fun getTime(): String? {
return “Current Time: ” + timepicker.currentHour.toString() + “:” +
timepicker.currentMinute.toString()
}
}
Output
Custom check box
You are able to create custom CheckBox in android. So, you can add some different
images of checkbox on the layout. For this you have to make another xml file and
add that file in button tag inside checkbox in main xml file.
Example
xml 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=”.MainActivity4″>
<CheckBox
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Educated”
android:layout_centerHorizontal=”true”
android:id=”@+id/cBEdu”
android:layout_marginTop=”50dp”
android:button=”@drawable/customcheckbox”/>
<CheckBox
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Uneducated”
android:layout_centerHorizontal=”true”
android:layout_below=”@+id/cBEdu”
android:button=”@drawable/customcheckbox”/>
</RelativeLayout>
Java code
package com.example.notescode
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class MainActivity4 : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main4)
}
}
customcheckbox.xml
<?xml version=”1.0″ encoding=”utf-8″?>
<selector xmlns:android=”http://schemas.android.com/apk/res/android”>
<item android:state_checked=”true” android:drawable=”@drawable/checked” />
<item android:state_checked=”false”
android:drawable=”@drawable/unchecked”/>
</selector>
Output
Dynamic radio button
We can also create radio button in android by using Kotlin/java only. We don’t need
to write xml code.
Example
xml 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=”.MainActivity5″
android:id=”@+id/relativeLayout”>
</RelativeLayout>
Java code
package com.example.notescode
import android.app.ActionBar
import android.os.Bundle
import android.widget.RadioButton
import android.widget.RadioGroup
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
class MainActivity5 : AppCompatActivity() {
private lateinit var radioGroup:RadioGroup
private lateinit var relLay:RelativeLayout
private lateinit var btn1:RadioButton
private lateinit var btn2:RadioButton
private lateinit var tv:TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main5)
radioGroup = RadioGroup(this)
relLay = findViewById(R.id.relativeLayout)
btn1 = RadioButton(this)
btn2 = RadioButton(this)
tv = TextView(this)
btn1.text = “Male”
btn2.text = “Female”
tv.text = “Gender”
radioGroup.addView(btn1)
radioGroup.addView(btn2)
radioGroup.orientation = RadioGroup.HORIZONTAL
val paramsRadioBtn = RelativeLayout.LayoutParams(
ActionBar.LayoutParams.WRAP_CONTENT,
ActionBar.LayoutParams.WRAP_CONTENT
)
val paramsTextView = RelativeLayout.LayoutParams(
ActionBar.LayoutParams.WRAP_CONTENT,
ActionBar.LayoutParams.WRAP_CONTENT
)
paramsTextView.leftMargin = 100
paramsTextView.topMargin = 100
paramsRadioBtn.leftMargin = 100
paramsRadioBtn.topMargin = 200
tv.layoutParams = paramsTextView
radioGroup.layoutParams = paramsRadioBtn
relLay.addView(tv)
relLay.addView(radioGroup)
}
}
Output
Custom radio button
Like custom checkbox we can also create custom radio button.
Example
customcheckbox.xml
<?xml version=”1.0″ encoding=”utf-8″?>
<selector xmlns:android=”http://schemas.android.com/apk/res/android”>
<item android:state_checked=”true” android:drawable=”@drawable/checked” />
<item android:state_checked=”false”
android:drawable=”@drawable/unchecked”/>
</selector>
xml
<?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=”.MainActivity5″
android:id=”@+id/relativeLayout”>
<RadioGroup
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_centerHorizontal=”true”
android:layout_marginTop=”50dp”>
<RadioButton
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Male”
android:id=”@+id/maleRadioBtn”
android:button=”@drawable/customcheckbox”/>
<RadioButton
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Female”
android:id=”@+id/femaleRadioBtn”
android:button=”@drawable/customcheckbox”/>
</RadioGroup>
</RelativeLayout>
Java code
package com.example.notescode
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
class MainActivity5 : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main5)
}
}
Output
List view / Custom list view
Android ListView is a view which contains the group of items and displays in a
scrollable list. ListView is implemented by importing android.widget.ListView class.
ListView is a default scrollable which does not use other scroll view.
ListView uses Adapter classes which add the content from data source (such as string
array, array, database etc) to ListView. Adapter bridges data between
an AdapterViews and other Views (ListView, ScrollView etc).
Example
xml 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=”.MainActivity2″>
<ListView
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:id=”@+id/myList”>
</ListView>
</RelativeLayout>
Java code
package com.example.notescode
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.AdapterView
import android.widget.ListView
import android.widget.Toast
class MainActivity2 : AppCompatActivity() {
private lateinit var list:ListView
private var title = arrayOf(“Title1”, “Title2”, “Title3”, “Title4”, “Title5”, “Title6”,
“Title7”, “Title8”, “Title9”, “Title10”)
private var imgArr = arrayOf<Int>(R.drawable.ic_launcher_background,
R.drawable.ic_launcher_background, R.drawable.ic_launcher_background,
R.drawable.ic_launcher_background, R.drawable.ic_launcher_background,
R.drawable.ic_launcher_background, R.drawable.ic_launcher_background,
R.drawable.ic_launcher_background, R.drawable.ic_launcher_background,
R.drawable.ic_launcher_background)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main2)
bindingElements()
val obj = MyListAdapter(this, title, imgArr)
list.adapter = obj
list.setOnItemClickListener { adapterView, view, position, id ->
val itemAtPos = adapterView.getItemAtPosition(position)
val itemIdAtPos = adapterView.getItemIdAtPosition(position)
Toast.makeText(this, “You select item $itemAtPos”,
Toast.LENGTH_LONG).show()
}
}
private fun bindingElements() {
list = findViewById(R.id.myList)
}
}
MyListAdapter.kt
package com.example.notescode
import android.app.Activity
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.ImageView
import android.widget.TextView
class MyListAdapter(context: Activity, mainTitle: Array<String>, imgId:
Array<Int>): ArrayAdapter<String>(context, R.layout.my_list, mainTitle) {
private val context: Activity
private val mainTitle: Array<String>
private val imgId: Array<Int>
init {
this.context=context
this.mainTitle=mainTitle
this.imgId=imgId
}
override fun getView(position: Int, view: View?, parent: ViewGroup): View {
val li = context.layoutInflater
val view = li.inflate(R.layout.my_list, null, true)
val titleText = view.findViewById(R.id.name) as TextView
val imageView = view.findViewById(R.id.imageIcon) as ImageView
titleText.text = mainTitle[position]
imageView.setImageResource(imgId[position])
return view
}
}
Output
WebView in android
Using webview we can display web inside android app. It is used to display online
content in android.
loadUrl() and loadData() methods of android WebView class are used to load and
display web pages.
WebView –> AbsoluteLayout -> ViewGroup -> View -> Object
Example
xml code
<?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=”.MainActivity6″>
<WebView
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:id=”@+id/webView” />
</androidx.constraintlayout.widget.ConstraintLayout>
Java code
package com.example.notescode
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.webkit.WebView
class MainActivity6 : AppCompatActivity() {
private lateinit var myWebView: WebView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main6)
myWebView = findViewById(R.id.webView)
myWebView.loadUrl(“https://www.google.com/”)
}
}
We also have to take internet permission in our android app for this we have to add
<uses-permission android:name=”android.permission.INTERNET”/> this in out
manifest file.
Output
SeekBar
Android SeekBar is a kind of ProgressBar with draggable thumb. The end user
can drag the thum left and right to move the progress of song, file download etc.
The SeekBar.OnSeekBarChangeListener interface provides methods to perform even
handling for seek bar.
SeekBar -> AbsSeekBar -> ProgressBar -> View -> Object
Example
xml 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=”.MainActivity6″>
<SeekBar
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:id=”@+id/seekBar”/>
</RelativeLayout>
Java code
package com.example.notescode
import android.os.Bundle
import android.widget.SeekBar
import android.widget.SeekBar.OnSeekBarChangeListener
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class MainActivity6 : AppCompatActivity() {
private lateinit var seekBar:SeekBar
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main6)
seekBar = findViewById(R.id.seekBar)
seekBar.setOnSeekBarChangeListener(object : OnSeekBarChangeListener {
override fun onProgressChanged(
seekBar: SeekBar, progress: Int,
fromUser: Boolean
) {
Toast.makeText(
applicationContext,
“seekbar progress: $progress”,
Toast.LENGTH_SHORT
).show()
}
override fun onStartTrackingTouch(seekBar: SeekBar) {
Toast.makeText(applicationContext, “seekbar touch started!”,
Toast.LENGTH_SHORT)
.show()
}
override fun onStopTrackingTouch(seekBar: SeekBar) {
Toast.makeText(applicationContext, “seekbar touch stopped!”,
Toast.LENGTH_SHORT)
.show()
}
})
}
}
Output
Analog and Digital clock
The android.widget.AnalogClock and android.widget.DigitalClock classes
provides the functionality to display analog and digital clocks.
Example
xml 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=”.MainActivity6″>
<SeekBar
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:id=”@+id/seekBar”
android:layout_marginTop=”50dp”/>
<DigitalClock
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:textSize=”50dp”
android:layout_centerHorizontal=”true”
android:layout_below=”@+id/seekBar”
android:id=”@+id/digitalClock”
android:layout_marginTop=”50dp”/>
<AnalogClock
android:id=”@+id/analogClock”
android:layout_width=”wrap_content”
android:layout_marginTop=”50dp”
android:layout_height=”wrap_content”
android:layout_below=”@id/digitalClock”
android:layout_centerHorizontal=”true” />
</RelativeLayout>
Design
Android ScrollView (Vertical)
The android.widget.ScrollView class provides the functionality of scroll view.
ScrollView is used to scroll the child elements of palette inside ScrollView.
Example
xml 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=”.MainActivity3″>
<ScrollView
android:layout_width=”match_parent”
android:layout_height=”match_parent”>
<LinearLayout
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:orientation=”vertical”
android:gravity=”center”>
<TimePicker
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_marginTop=”20dp”
android:id=”@+id/timePicker”
android:layout_marginLeft=”30dp”
android:layout_marginRight=”30dp”/>
<DatePicker
android:id=”@+id/datePicker”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_marginTop=”20dp” />
<Button
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Show Date and Time”
android:id=”@+id/showBtn”
android:layout_marginTop=”20dp” />
</LinearLayout>
</ScrollView>
</RelativeLayout>
Design
Android ScrollView (Horizontal)
We also have horizontal scroll view similar to vertical scroll view in android.
Example
xml 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=”.MainActivity6″>
<SeekBar
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:id=”@+id/seekBar”
android:layout_marginTop=”50dp”/>
<DigitalClock
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:textSize=”50dp”
android:layout_centerHorizontal=”true”
android:layout_below=”@+id/seekBar”
android:id=”@+id/digitalClock”
android:layout_marginTop=”50dp”/>
<AnalogClock
android:id=”@+id/analogClock”
android:layout_width=”200dp”
android:layout_marginTop=”50dp”
android:layout_height=”200dp”
android:layout_below=”@id/digitalClock”
android:layout_centerHorizontal=”true” />
<HorizontalScrollView
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:layout_marginTop=”50dp”
android:layout_marginRight=”10dp”
android:layout_marginLeft=”10dp”
android:id=”@+id/horizontalScrollView”
android:layout_below=”@id/analogClock”>
<LinearLayout
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:orientation=”horizontal”>
<Button
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Button One” />
<Button
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Button Two” />
<Button
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Button Three” />
<Button
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Button Four” />
<Button
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Button Five” />
<Button
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Button Six” />
</LinearLayout>
</HorizontalScrollView>
</RelativeLayout>
Output
ProgressBar
It is used to show the status of work. We can display status of work using progress
bar. Ex. File downloading, etc.
The ProgressDialog class provides methods to work on progress bar like
setProgress(), setMessage(), setProgressStyle(), setMax(), show() etc. The progress
range of Progress Dialog is 0 to 10000.
ProgressBar -> AlertDialog -> Dialog -> object
Example
xml 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=”.MainActivity7″>
<Button
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_centerHorizontal=”true”
android:layout_marginTop=”20dp”
android:id=”@+id/progressBarBtn”
android:text=”Download”
android:backgroundTint=”@color/teal_200″
android:textSize=”20sp” />
</RelativeLayout>
Java code
package com.example.notescode
import android.app.ProgressDialog
import android.os.Bundle
import android.os.Handler
import android.view.View
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
class MainActivity7 : AppCompatActivity() {
private lateinit var btn:Button
private lateinit var progressBar:ProgressDialog
private var progressStatus:Int = 0
private var handler:Handler = Handler()
private var fileSize:Int = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main7)
addClicks()
}
private fun addClicks() {
btn = findViewById(R.id.progressBarBtn)
btn.setOnClickListener(View.OnClickListener {
progressBar = ProgressDialog(it.context)
progressBar.setCancelable(true)
progressBar.setMessage(“File Downloading …”)
progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL)
progressBar.progress = 0
progressBar.max = 100
progressBar.show()
progressStatus = 0
fileSize = 0
Thread {
while (progressStatus < 100) {
progressStatus = doOperation()
try {
Thread.sleep(1000)
} catch (e: InterruptedException) {
e.printStackTrace()
}
handler.post(Runnable { progressBar.progress = progressStatus })
}
if (progressStatus >= 100) {
try {
Thread.sleep(1000)
} catch (e: InterruptedException) {
e.printStackTrace()
}
progressBar.dismiss()
}
}.start()
})
}
private fun doOperation(): Int{
while (fileSize <= 10000){
fileSize++
when (fileSize) {
1000 -> {
return 10;
}
2000 -> {
return 20
}
3000 -> {
return 30
}
4000 -> {
return 40
}
}
}
return 100
}
}
Output
ViewStub
A ViewStub is a zero-sized invisible View which is used to load “layout resource” at
runtime. ViewStub is a zero dimension View, so you will not see anything on the
layout pallete.
Example
xml 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=”.MainActivity9″>
<ViewStub
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:id=”@+id/viewStub”
android:layout=”@layout/my_layout”
android:layout_centerHorizontal=”true”
android:layout_marginTop=”20dp”/>
<LinearLayout
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_alignParentBottom=”true”
android:layout_marginBottom=”20dp”
android:orientation=”horizontal”
android:layout_centerHorizontal=”true”>
<Button
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Show”
android:id=”@+id/showBtn”/>
<Button
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Hide”
android:id=”@+id/hideBtn”
android:layout_marginLeft=”20dp”/>
</LinearLayout>
</RelativeLayout>
my_layout.xml
<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:gravity=”center”
android:orientation=”vertical”>
<TextView
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Abhishek Bansal”
android:textSize=”20sp”/>
<ImageView
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_marginTop=”20dp”
android:src=”@drawable/ic_launcher_foreground”/>
</LinearLayout>
Java code
package com.example.notescode
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.view.ViewStub
import android.widget.Button
class MainActivity9 : AppCompatActivity() {
private lateinit var viewStub:ViewStub
private lateinit var btnShow:Button
private lateinit var btnHide:Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main9)
viewStub = findViewById(R.id.viewStub)
btnShow = findViewById(R.id.showBtn)
btnHide = findViewById(R.id.hideBtn)
viewStub.inflate()
btnShow.setOnClickListener(View.OnClickListener {
viewStub.visibility = View.VISIBLE
})
btnHide.setOnClickListener(View.OnClickListener {
viewStub.visibility = View.GONE
})
}
}
Output
Android RecyclerView
Android image switcher provides an animation over images to transition from one
image to another. In order to use image switcher, we need to implement
ImageSwitcher component in .xml file.
Example
xml
<?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=”.MainActivity8″>
<TextView
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Image Switcher Example”
android:id=”@+id/textView”
android:textSize=”30sp”
android:layout_alignParentTop=”true”
android:layout_centerHorizontal=”true”
android:layout_marginTop=”10dp”/>
<ImageSwitcher
android:id=”@+id/imageSwitcher”
android:layout_width=”match_parent”
android:layout_height=”250dp”
android:layout_below=”@id/textView”
android:layout_margin=”40dp” />
<Button
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Next”
android:id=”@+id/buttonNext”
android:layout_marginTop=”20dp”
android:layout_below=”@id/imageSwitcher”
android:layout_centerHorizontal=”true” />
<Button
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Prev”
android:id=”@+id/buttonPrev”
android:layout_marginTop=”10dp”
android:layout_below=”@id/buttonNext”
android:layout_centerHorizontal=”true” />
</RelativeLayout>
Java code
package com.example.notescode
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.view.animation.AnimationUtils
import android.widget.Button
import android.widget.ImageSwitcher
import android.widget.ImageView
import android.widget.ViewSwitcher
class MainActivity8 : AppCompatActivity() {
private lateinit var imageSwitcher: ImageSwitcher
private lateinit var nextButton: Button
private lateinit var prevButton:Button
private val imagesArr = arrayOf<Int>(R.drawable.ic_launcher_background,
R.drawable.checked, R.drawable.ic_launcher_foreground)
private var index = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main8)
imageSwitcher = findViewById(R.id.imageSwitcher)
nextButton = findViewById(R.id.buttonNext)
prevButton = findViewById(R.id.buttonPrev)
imageSwitcher.setFactory {
val imgView = ImageView(applicationContext)
imgView.scaleType = ImageView.ScaleType.FIT_CENTER
imgView.setPadding(8, 8, 8, 8)
imgView
}
imageSwitcher.setImageResource(imagesArr[index])
val imgIn = AnimationUtils.loadAnimation(
this, android.R.anim.slide_in_left
)
imageSwitcher.inAnimation = imgIn
val imgOut = AnimationUtils.loadAnimation(
this, android.R.anim.slide_out_right
)
imageSwitcher.outAnimation = imgOut
prevButton.setOnClickListener(View.OnClickListener {
index = if(index – 1 >= 0) index-1 else 2
imageSwitcher.setImageResource(imagesArr[index])
})
nextButton.setOnClickListener(View.OnClickListener {
index = if(index + 1 <imagesArr.size) index+1 else 2
imageSwitcher.setImageResource(imagesArr[index])
})
}
}
Output
Android ImageSlider
Image slider is seen in most e-commerce applications that display advertisements on
the home screen. This slider displays the advertisement banners which users can
slide to view the others.
Example
xml
<?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=”.MainActivity10″>
<androidx.viewpager.widget.ViewPager
android:layout_width=”300dp”
android:layout_height=”300dp”
android:layout_centerInParent=”true”
android:layout_margin=”10dp”
android:id=”@+id/viewPager”/>
</RelativeLayout>
view_pager.xml
<?xml version=”1.0″ encoding=”utf-8″?>
<RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”match_parent”
android:layout_height=”match_parent”>
<ImageView
android:id=”@+id/imageViewViewPager”
android:layout_width=”200dp”
android:layout_height=”200dp”
android:layout_centerInParent=”true” />
</RelativeLayout>
ViewPagerAdapter
package com.example.notescode
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.RelativeLayout
import androidx.viewpager.widget.PagerAdapter
import java.util.*
class ViewPagerAdapter (val context:Context, val imageList:List<Int>) :
PagerAdapter() {
override fun getCount(): Int {
return imageList.size
}
override fun isViewFromObject(view: View, `object`: Any): Boolean {
return view === `object` as RelativeLayout
}
override fun instantiateItem(container: ViewGroup, position: Int): Any {
val mLayoutInflater =
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as
LayoutInflater
val itemView: View = mLayoutInflater.inflate(R.layout.view_pager, container,
false)
val imageView: ImageView =
itemView.findViewById<View>(R.id.imageViewViewPager) as ImageView
imageView.setImageResource(imageList.get(position))
Objects.requireNonNull(container).addView(itemView)
return itemView
}
override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
container.removeView(`object` as RelativeLayout)
}
}
Java code
package com.example.notescode
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.viewpager.widget.ViewPager
class MainActivity10 : AppCompatActivity() {
lateinit var viewPager: ViewPager
lateinit var viewPagerAdapter: ViewPagerAdapter
lateinit var imageList: List<Int>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main10)
viewPager = findViewById(R.id.viewPager)
imageList = ArrayList<Int>()
imageList = imageList + R.drawable.ic_launcher_foreground
imageList = imageList + R.drawable.checked
imageList = imageList + R.drawable.unchecked
imageList = imageList + R.drawable.ic_launcher_background
viewPagerAdapter = ViewPagerAdapter(applicationContext, imageList)
viewPager.adapter = viewPagerAdapter
}
}
Output
Android TabLayout
TabLayout is used to implement horizontal tabs. Like below –
Example
xml code
<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout 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=”.MainActivity11″
android:orientation=”vertical”>
<com.google.android.material.tabs.TabLayout
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:id=”@+id/tabLayout”>
</com.google.android.material.tabs.TabLayout>
<androidx.viewpager.widget.ViewPager
android:layout_width=”355dp”
android:layout_height=”455dp”
android:id=”@+id/viewPager”/>
</LinearLayout>
Adapter class
package com.example.notescode
import android.content.Context
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
class MyAdapterForTabLayout (context:Context, fm:FragmentManager,
totalTabs:Int) : FragmentPagerAdapter(fm) {
private var myContext:Context
private var totalTabs:Int
init {
myContext = context
this.totalTabs = totalTabs
}
override fun getCount(): Int {
return totalTabs
}
override fun getItem(position: Int): Fragment {
return when (position) {
0 -> HomeFragment()
1 -> SportFragment()
2 -> MovieFragment()
else -> null
}
}
}
Java code
package com.example.notescode
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.viewpager.widget.ViewPager
import com.google.android.material.tabs.TabLayout
class MainActivity11 : AppCompatActivity() {
private lateinit var tabLayout:TabLayout
private lateinit var viewPager:ViewPager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main11)
tabLayout=findViewById(R.id.tabLayout)
viewPager=findViewById(R.id.viewPager)
tabLayout.addTab(tabLayout.newTab().setText(“Home”))
tabLayout.addTab(tabLayout.newTab().setText(“Sport”))
tabLayout.addTab(tabLayout.newTab().setText(“Movie”))
tabLayout.tabGravity = TabLayout.GRAVITY_FILL
val adapter = MyAdapterForTabLayout(this, supportFragmentManager,
tabLayout!!.tabCount)
viewPager.adapter = adapter
viewPager.addOnPageChangeListener(TabLayout.TabLayoutOnPageChangeListener
(tabLayout))
tabLayout.addOnTabSelectedListener(object :
TabLayout.OnTabSelectedListener {
override fun onTabSelected(tab: TabLayout.Tab) {
viewPager.currentItem = tab.position
}
override fun onTabUnselected(tab: TabLayout.Tab) {
}
override fun onTabReselected(tab: TabLayout.Tab) {
}
})
}
}
We have to create all different fragments to show in different tabs.
Output
Android RecyclerView
The RecyclerView class extends the ViewGroup class and implements ScrollingView
interface. It is an advanced version of the ListView with improved performance and
other benefits.
Example
xml code
<?xml version=”1.0″ encoding=”utf-8″?>
<androidx.recyclerview.widget.RecyclerView
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:id=”@+id/myRecyclerView”
tools:context=”.MainActivity12″>
</androidx.recyclerview.widget.RecyclerView>
Adapter class
package com.example.notescode
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.recyclerview.widget.RecyclerView
class RecyclerViewAdapter(listData: Array<MyList>) :
RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>() {
private var listData: Array<MyList>
init {
this.listData=listData
}
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): RecyclerViewAdapter.ViewHolder {
val layoutInflater: LayoutInflater = LayoutInflater.from(parent.context)
val listItem: View = layoutInflater.inflate(R.layout.recycler_view_layout,
parent, false)
return ViewHolder(listItem)
}
override fun onBindViewHolder(holder: RecyclerViewAdapter.ViewHolder,
position: Int) {
val data: MyList = listData[position]
holder.textView.text = listData[position].getName()
holder.imageView.setImageResource(listData[position].getImgId())
holder.relativeLayout.setOnClickListener(View.OnClickListener {
Toast.makeText(it.context, “Click on item: ${data.getName()}”,
Toast.LENGTH_LONG).show()
})
}
override fun getItemCount(): Int {
return listData.size
}
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var imageView: ImageView
var textView: TextView
var relativeLayout: RelativeLayout
init {
imageView = itemView.findViewById<View>(R.id.myImgViewRV) as
ImageView
textView = itemView.findViewById<View>(R.id.myTextViewRV) as TextView
relativeLayout = itemView.findViewById<View>(R.id.relativeLayout) as
RelativeLayout
}
}
}
Recycler View Layout
<?xml version=”1.0″ encoding=”utf-8″?>
<RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:id=”@+id/relativeLayout”
android:layout_width=”match_parent”
android:layout_height=”?android:attr/listPreferredItemHeightLarge”>
<ImageView
android:id=”@+id/myImgViewRV”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_centerVertical=”true”
android:layout_alignParentStart=”true”
android:layout_alignParentLeft=”true”
android:contentDescription=”Icon” />
<TextView
android:id=”@+id/myTextViewRV”
android:layout_width=”wrap_content”
android:layout_height=”match_parent”
android:layout_toEndOf=”@id/myImgViewRV”
android:layout_toRightOf=”@id/myImgViewRV”
android:gravity=”center_vertical”
android:textSize=”16sp”/>
</RelativeLayout>
MyList class
package com.example.notescode
class MyList(name:String, id:Int) {
private var name:String
private var imgId:Int
init {
this.name = name
imgId = id
}
fun getName():String{
return name
}
fun setName(name:String){
this.name=name
}
fun getImgId():Int{
return imgId
}
fun setImgId(id:Int){
this.imgId = id
}
}
Main class
package com.example.notescode
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
class MainActivity12 : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main12)
val myListData: Array<MyList> = arrayOf<MyList>(
MyList(“Email”, android.R.drawable.ic_dialog_email),
MyList(“Info”, android.R.drawable.ic_dialog_info),
MyList(“Delete”, android.R.drawable.ic_delete),
MyList(“Dialer”, android.R.drawable.ic_dialog_dialer),
MyList(“Alert”, android.R.drawable.ic_dialog_alert),
MyList(“Map”, android.R.drawable.ic_dialog_map),
MyList(“Email”, android.R.drawable.ic_dialog_email),
MyList(“Info”, android.R.drawable.ic_dialog_info),
MyList(“Delete”, android.R.drawable.ic_delete),
MyList(“Dialer”, android.R.drawable.ic_dialog_dialer),
MyList(“Alert”, android.R.drawable.ic_dialog_alert),
MyList(“Map”, android.R.drawable.ic_dialog_map)
)
var recyclerView: RecyclerView = findViewById(R.id.myRecyclerView)
var adapter: RecyclerViewAdapter = RecyclerViewAdapter(myListData)
recyclerView.setHasFixedSize(true)
recyclerView.layoutManager = LinearLayoutManager(this);
recyclerView.adapter = adapter
}
}
Output
Android Activity Lifecycle
Its lifecycle is controlled by seven methods of android.app.Activity class. An activity
is a single screen in android. It is like window or frame of java.
Activity -> ContextThemeWrapper -> ContextWrapper -> Context -> Object
Seven methods1. onCreate – called when activity is first created.
2. onStart – called when activity is become visible to user.
3. onResume – called when activity start interacting with user.
4. onPause – called when activity is not visible to user.
5. onStop – called when activity is no longer visible to user.
6. onRestart – called after your activity is stopped, prior to start.
7. onDestroy – called before the activity is destroyed.
Android Intent
An Intent is the message that is passed between components such as activities,
content providers, broadcast receivers, services etc.
Intents are mainly used to –
1. Start the activity
2. Launch the activity
3. Display a web page
4. Display a list of contacts
5. Broadcast a message
6. Dial a phone call etc.
Types of intents –
1. Implicit intent
2. Explicit intent
Implicit intent
Using implicit Intent, components can’t be specified. An action to be performed is
declared by implicit intent. Then android operating system will filter out
components that will respond to the action.
Example –
val intent:Intent = Intent(Intent.ACTION_VIEW)
intent.setData(Uri.parse(“http://www.javatpoint.com”))
startActivity(intent)
Explicit intent
Using explicit Intent, components can be specified. In such case, intent provides the
external class to be invoked.
Example –
val intent:Intent = Intent(applicationContext, ActivityTwo::class.java);
startActivity(intent);;
StartActivityForResult
By the help of android startActivityForResult() method, we can get result from
another activity.
By the help of android startActivityForResult() method, we can send information
from one activity to another and vice-versa. The android
startActivityForResult method, requires a result from the second activity (activity to
be invoked).
In such case, we need to override the onActivityResult method that is invoked
automatically when second activity returns result.
Share App Data
Android uses ACTION_SEND event of android.content.Intent class to send data
from one activity to another and from current activity to outside the application.
Intent class needs to specify the data and its type which is to be share.
Example –
xml 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=”.MainActivity19″>
<Button
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Share”
android:id=”@+id/shareBtn”
android:layout_centerInParent=”true”/>
</RelativeLayout>
Java code
package com.example.notescode
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
class MainActivity19 : AppCompatActivity() {
lateinit var btn:Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main19)
btn = findViewById(R.id.shareBtn)
btn.setOnClickListener(View.OnClickListener {
val intentShare:Intent = Intent(android.content.Intent.ACTION_SEND)
intentShare.setType(“text/plain”)
intentShare.putExtra(Intent.EXTRA_SUBJECT,”Insert subject here”)
val url = “www.google.com”
intentShare.putExtra(android.content.Intent.EXTRA_TEXT, url)
startActivity(Intent.createChooser(intentShare, “Share via”))
})
}
}
Output
Android Fragments
Android Fragment is the part of activity, it is also known as sub-activity. There
can be more than one fragment in an activity. Fragments represent multiple screen
inside one activity.
Android fragment lifecycle is affected by activity lifecycle because fragments are
included in activity.
Each fragment has its own life cycle methods that is affected by activity life cycle
because fragments are embedded in activity.
The FragmentManager class is responsible to make interaction between fragment
objects.
Life cycle –
1. onAttach(Activity) – it is called only once when it is attached with activity.
2. onCreate(Bundle) – it is used to initialize the fragment.
3. onCreateView(LayoutInflater, ViewGroup, Bundle) – create and return view
hirerchy.
4. onActivityCreated(Bundle) – it is invoked after the completion of onCreate()
method.
5. onViewStateRestore(Bundle) – It provides information to the fragment that all
the saved state of fragment view hierarchy has been restored.
6. onStart() – makes the fragment visible.
7. onResume() – makes the fragment interactive.
8. onPause() – is calles when fragment is no longer interactive.
9. onStop() – is called when fragment is no longer visible.
10. onDestroyView – allows the fragment to clean up resources.
11. onDestroy() – allows the fragment to do final clean up of fragment state.
12. onDetach() – It is called immediately prior to the fragment no longer being
associated with its activity.
Example –
xml code
<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout 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=”.MainActivity11″
android:orientation=”vertical”>
<com.google.android.material.tabs.TabLayout
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:id=”@+id/tabLayout”>
</com.google.android.material.tabs.TabLayout>
<androidx.viewpager.widget.ViewPager
android:layout_width=”355dp”
android:layout_height=”455dp”
android:id=”@+id/viewPager”/>
</LinearLayout>
Adapter class
package com.example.notescode
import android.content.Context
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
class MyAdapterForTabLayout (context:Context, fm:FragmentManager,
totalTabs:Int) : FragmentPagerAdapter(fm) {
private var myContext:Context
private var totalTabs:Int
init {
myContext = context
this.totalTabs = totalTabs
}
override fun getCount(): Int {
return totalTabs
}
override fun getItem(position: Int): Fragment {
return when (position) {
0 -> HomeFragment()
1 -> SportFragment()
2 -> MovieFragment()
else -> null
}
}
}
Java code
package com.example.notescode
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.viewpager.widget.ViewPager
import com.google.android.material.tabs.TabLayout
class MainActivity11 : AppCompatActivity() {
private lateinit var tabLayout:TabLayout
private lateinit var viewPager:ViewPager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main11)
tabLayout=findViewById(R.id.tabLayout)
viewPager=findViewById(R.id.viewPager)
tabLayout.addTab(tabLayout.newTab().setText(“Home”))
tabLayout.addTab(tabLayout.newTab().setText(“Sport”))
tabLayout.addTab(tabLayout.newTab().setText(“Movie”))
tabLayout.tabGravity = TabLayout.GRAVITY_FILL
val adapter = MyAdapterForTabLayout(this, supportFragmentManager,
tabLayout!!.tabCount)
viewPager.adapter = adapter
viewPager.addOnPageChangeListener(TabLayout.TabLayoutOnPageChangeListener
(tabLayout))
tabLayout.addOnTabSelectedListener(object :
TabLayout.OnTabSelectedListener {
override fun onTabSelected(tab: TabLayout.Tab) {
viewPager.currentItem = tab.position
}
override fun onTabUnselected(tab: TabLayout.Tab) {
}
override fun onTabReselected(tab: TabLayout.Tab) {
}
})
}
}
We have to create all different fragments to show in different tabs.
Output
Android Service
Android service is a component that is used to perform operations on the
background such as playing music, handle network transactions, interacting content
providers etc. It doesn’t has any UI (user interface).
Service -> ContextWrapper -> Context -> Object
Example –
xml code
<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout 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=”.MainActivity21″
android:orientation=”vertical”
android:gravity=”center”>
<Button
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Play”
android:padding=”20dp”
android:id=”@+id/playSong”/>
<Button
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Stop”
android:padding=”20dp”
android:id=”@+id/stopSong”/>
</LinearLayout>
Java code
package com.example.notescode
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
class MainActivity21 : AppCompatActivity(), View.OnClickListener {
lateinit var startBtn:Button
lateinit var stopBtn:Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main21)
startBtn = findViewById(R.id.playSong)
stopBtn = findViewById(R.id.stopSong)
startBtn.setOnClickListener(this)
stopBtn.setOnClickListener(this)
}
override fun onClick(id: View?) {
when(id!!.id){
R.id.playSong ->{
startService(Intent(this, MyService::class.java))
}
R.id.stopSong ->{
stopService(Intent(this, MyService::class.java))
}
}
}
}
Sercive class
package com.example.notescode
import android.app.Service
import android.content.Intent
import android.media.MediaPlayer
import android.os.IBinder
import android.widget.Toast
class MyService: Service() {
lateinit var myPlayer:MediaPlayer
override fun onBind(p0: Intent?): IBinder? {
return null
}
override fun onCreate() {
Toast.makeText(this, “Song added”, Toast.LENGTH_LONG).show()
myPlayer = MediaPlayer.create(this, R.raw.song)
myPlayer.isLooping = false
}
override fun onStart(intent: Intent?, startId: Int) {
Toast.makeText(this, “Song start”, Toast.LENGTH_LONG).show()
myPlayer.start()
}
override fun onDestroy() {
Toast.makeText(this, “Song stop”, Toast.LENGTH_LONG).show()
myPlayer.stop()
}
}
Output
Click on play song will be played.
Click on stop song will be stoped.
Android AlarmManager
Android AlarmManager allows you to access system alarm.
By the help of Android AlarmManager in android, you can schedule your
application to run at a specific time in the future. It works whether your phone is
running or not.
The Android AlarmManager holds a CPU wake lock that provides guarantee not to
sleep the phone until broadcast is handled.
Example –
xml code
<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout 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=”.MainActivity22″
android:orientation=”vertical”
android:gravity=”center”>
<EditText
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:hint=”Enter time”
android:layout_margin=”20dp”
android:id=”@+id/timeBR”/>
<Button
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Start”
android:id=”@+id/songStartBtn”/>
<Button
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Stop”
android:id=”@+id/songStopBtn”/>
</LinearLayout>
Java code
package com.example.notescode
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
class MainActivity22 : AppCompatActivity() {
lateinit var btnStart:Button
lateinit var btnStop:Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main22)
btnStart = findViewById(R.id.songStartBtn)
btnStop = findViewById(R.id.songStopBtn)
btnStart.setOnClickListener(View.OnClickListener {
startSong()
})
btnStop.setOnClickListener(View.OnClickListener {
stopSong()
})
}
private fun stopSong() {
}
private fun startSong() {
val timeEt = findViewById<EditText>(R.id.timeBR)
val time:Int = Integer.valueOf(timeEt.text.toString())
val intent:Intent = Intent(this, MyBroadcastReceiver::class.java)
val pendingIntent:PendingIntent =
PendingIntent.getBroadcast(applicationContext, 234324243, intent, 0)
val alarmManager:AlarmManager = getSystemService(ALARM_SERVICE) as
AlarmManager
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
+ (time*1000), pendingIntent)
Toast.makeText(this, “Song will start in $time seconds”,
Toast.LENGTH_LONG).show()
}
}
MyBroadCastReceiver class
package com.example.notescode
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.media.MediaPlayer
import android.widget.Toast
class MyBroadcastReceiver:BroadcastReceiver() {
private lateinit var myPlayer:MediaPlayer
override fun onReceive(p0: Context?, p1: Intent?) {
myPlayer = MediaPlayer.create(p0, R.raw.song)
myPlayer.start()
Toast.makeText(p0, “Song start”, Toast.LENGTH_LONG).show()
}
}
Output –
When you click on start button song will start after the time entered by user.
Click on stop song will be stopped.
Android SharedPreferences
Android shared preference is used to store and retrieve primitive information. In
android, string, integer, long, number etc. are considered as primitive data type.
Android Shared preferences are used to store data in key and value pair so that we
can retrieve the value on the basis of key.
Example –
xml code
<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout 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:gravity=”center”
tools:context=”.MainActivity23″
android:orientation=”vertical”>
<Button
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Store”
android:id=”@+id/storeInfoBtn”/>
<Button
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Show”
android:id=”@+id/showInfoBtn”/>
<TextView
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:id=”@+id/data”/>
</LinearLayout>
Java code
package com.example.notescode
import android.content.Intent
import android.content.SharedPreferences
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.preference.PreferenceManager
import android.view.View
import android.widget.Button
import android.widget.TextView
import org.w3c.dom.Text
class MainActivity23 : AppCompatActivity() {
lateinit var showBtn:Button
lateinit var storeBtn:Button
lateinit var display:TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main23)
storeBtn = findViewById(R.id.storeInfoBtn)
showBtn = findViewById(R.id.showInfoBtn)
display = findViewById(R.id.data)
val listener = View.OnClickListener {
when(it.id){
R.id.storeInfoBtn ->{
startActivity(Intent(this, SharedPrefActivity::class.java))
}
R.id.showInfoBtn ->{
displayInfo()
}
}
}
storeBtn.setOnClickListener(listener)
showBtn.setOnClickListener(listener)
}
private fun displayInfo() {
val pref:SharedPreferences =
PreferenceManager.getDefaultSharedPreferences(this)
val userName:String = pref.getString(“username”, “Default
NickName”).toString()
val passw:String = pref.getString(“password”, “Default Password”).toString()
val builder:StringBuilder = StringBuilder()
builder.append(“Username$userName\n”)
builder.append(“Password$passw\n”)
display.text = builder.toString()
}
}
share_pref_activity.xml code
<?xml version=”1.0″ encoding=”utf-8″?>
<PreferenceScreen
xmlns:android=”http://schemas.android.com/apk/res/android”>
<PreferenceCategory
android:summary=”Username and password information”
android:title=”Login information” >
<EditTextPreference
android:key=”username”
android:summary=”Please enter your login username”
android:title=”Username” />
<EditTextPreference
android:key=”password”
android:summary=”Enter your password”
android:title=”Password” />
</PreferenceCategory>
</PreferenceScreen>
SharedPreferenceActivity class
package com.example.notescode
import android.os.Bundle
import android.preference.PreferenceActivity
class SharedPrefActivity:PreferenceActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
addPreferencesFromResource(R.xml.activity_shared_prefs)
}
}
Output –
Click on store button
Click on username button
Click on password button
Click on show button
Android Internal Storage
We are able to save or read data from the device internal memory. FileInputStream
and FileOutputStream classes are used to read and write data into the file.
Exmaple –
xml code
<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout 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=”.MainActivity24″
android:orientation=”vertical”
android:gravity=”center_horizontal”>
<EditText
android:layout_margin=”20dp”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:hint=”Enter file name”
android:id=”@+id/fileNameEt”/>
<EditText
android:layout_margin=”20dp”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:hint=”Enter file data”
android:id=”@+id/fileDataEt”/>
<Button
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Store”
android:id=”@+id/storeInFile”/>
<Button
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Show”
android:id=”@+id/showFromFile”/>
</LinearLayout>
Java code
package com.example.notescode
import android.content.Context
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import java.io.*
class MainActivity24 : AppCompatActivity() {
lateinit var fileName:EditText
lateinit var fileData:EditText
lateinit var store:Button
lateinit var showData:Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main24)
fileName = findViewById(R.id.fileNameEt)
fileData = findViewById(R.id.fileDataEt)
store = findViewById(R.id.storeInFile)
showData = findViewById(R.id.showFromFile)
store.setOnClickListener(View.OnClickListener {
val fileNameOne = fileName.text.toString()
val data = fileData.text.toString()
val fos:FileOutputStream
try{
fos = openFileOutput(fileNameOne, Context.MODE_PRIVATE)
fos.write(data.toByteArray())
fos.close()
Toast.makeText(this, fileNameOne + “saved”,
Toast.LENGTH_LONG).show()
}catch (e:FileNotFoundException){
e.printStackTrace()
}catch (e:IOException){
e.printStackTrace()
}
})
showData.setOnClickListener(View.OnClickListener {
val fileNameOne = fileName.text.toString()
val stringBuffer:StringBuffer = StringBuffer()
try {
val inputReader = BufferedReader(
InputStreamReader(
openFileInput(fileNameOne)
)
)
var inputString: String
while (inputReader.readLine().also { inputString = it } != null) {
stringBuffer.append(
“””
$inputString
“””.trimIndent()
)
}
} catch (e: IOException) {
e.printStackTrace()
}
Toast.makeText(this, stringBuffer.toString(), Toast.LENGTH_LONG).show()
})
}
}
Output –
When click on store button data will be stored in a file named hello and when clicked
on show button data will be displayed to user.