Blog About Kotlin Programming Language which is official language on Android. It's expressive, concise, and powerful. Best of all, it's interoperable with our existing Android languages and runtime.
Go to File => New => New Project.Give Name To your application. Then, check Include Kotlin Support and click next button.
Select minimum SDK you need. However, we have selected 21 as minimum SDK. Then, click next button.
Then, select Empty Activity => click next => click finish.
2.Here we have XML file activity_main.xml.WhichContain ListView.We Have to Perform Long Click on ListView Item to open Context Menu.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayoutxmlns: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:orientation="vertical"tools:context=".MainActivity"><TextViewandroid:layout_width="match_parent"android:layout_height="40sp"android:gravity="center"android:text="Long Press On List Item to Open Context Menu"android:textColor="@color/colorPrimary"android:textStyle="bold"app:layout_constraintBottom_toBottomOf="parent"app:layout_constraintLeft_toLeftOf="parent"app:layout_constraintRight_toRightOf="parent"app:layout_constraintTop_toTopOf="parent"/><ListViewandroid:id="@+id/listView"android:layout_width="match_parent"android:layout_height="match_parent"/></LinearLayout>
3.MainActivity.kt
packagecom.dharmendra.contextmenu
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.ContextMenu
import android.view.MenuItem
import android.view.View
import android.widget.AdapterView.AdapterContextMenuInfo
import android.widget.ArrayAdapter
import android.widget.ListView
import android.widget.Toast
classMainActivity : AppCompatActivity() {
lateinit var array: Array<String>
overridefunonCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//Find View By Id For ListViewval listView = findViewById<ListView>(R.id.listView) as ListView
//Array of String Which Contain Name of Persons.
array = arrayOf("Sachin", "Vishal", "Rishu", "Krishank", "Vivek", "Jatin", "Raj", "Rajan", "Nikhil")
//Creating Adapterval adp = ArrayAdapter(this@MainActivity, android.R.layout.simple_list_item_1, array)
//Set Adapter to ListView
listView.adapter = adp
//Register ListView for Context Menu
registerForContextMenu(listView)
}
overridefunonCreateContextMenu(menu: ContextMenu?, v: View?, menuInfo: ContextMenu.ContextMenuInfo?) {
super.onCreateContextMenu(menu, v, menuInfo)
//Set Header of Context Menu
menu!!.setHeaderTitle("Select Option")
menu.add(0, v!!.id, 0, "Call")
menu.add(0, v.id, 1, "SMS")
menu.add(0, v.id, 2, "Email")
menu.add(0, v.id, 3, "WhatsApp")
/* menu.add get 4 Parameters 1. grouId if you want to add multiple Group than for every group Id is Diffrent Here we have only One Group so We take 0(Zero) as GroupId 2.v.id is our Item Id 3. Set Order of Our Item(Position Of Item) if you Change order of Call to 1 and SMS to 0 than in Menu SMS Display First. 4. Title to Display on Context menu */
}
overridefunonContextItemSelected(item: MenuItem?): Boolean {
//Get Order of Selected Itemval selectedItemOrder = item!!.order
//Get Title Of Selected Itemval selectedItemTitle = item.title
//To get Name of Person Click on ListViewval info = item.menuInfo as AdapterContextMenuInfo
val listPosition = info.position
val name = array[listPosition]
Toast.makeText(this@MainActivity, " " + selectedItemTitle + " " + name, Toast.LENGTH_LONG).show()
returntrue
}
}
Go to File => New => New Project.Give Name To your application. Then, check Include Kotlin Support and click next button.
Select minimum SDK you need. However, we have selected 21 as minimum SDK. Then, click next button.
Then, select Empty Activity => click next => click finish.
2.Here we have one XML file activity_main.xml
activity_main.xml
<?xml version="1.0" encoding="utf-8"?><RelativeLayoutxmlns: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/relative"tools:context="com.dharmendra.optionmenu.MainActivity"><TextViewandroid:id="@+id/textView"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_centerHorizontal="true"android:layout_centerVertical="true"android:textSize="20sp"android:textStyle="bold"android:textColor="@android:color/black"android:text="Click On 3 Dots on Action Bar "/></RelativeLayout>
3.We need to create one more xml file inside res->menu folder.
First we have to Create folder name menu inside res folder. And inside menu folder we have to create xml file name option_menu.xml
option_menu Contain 5 Items first Two are to change Text Color and other 3 for change Background Color.
lateinit var textView:TextView
overridefunonCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//Find View By Id For TextView because We change the Color of text
textView=findViewById<TextView>(R.id.textView) as TextView
//Find View By Id For Main Layout because we chnage the Color of Backgroud
backgroud=findViewById<RelativeLayout>(R.id.relative) as RelativeLayout
}
overridefunonCreateOptionsMenu(menu: Menu?): Boolean {
//Inflate menu
menuInflater.inflate(R.menu.option_menu,menu)
returntrue
}
//Method to Handle Option Item ClickoverridefunonOptionsItemSelected(item: MenuItem?): Boolean {
val selectedItem= item!!.itemId
when(selectedItem){
R.id.magenta->{
//Change Text Color
textView.setTextColor(Color.MAGENTA)
}
R.id.yellow->{
//Change Text Color
textView.setTextColor(Color.YELLOW)
}
R.id.red->{
//Change Background Color
backgroud.setBackgroundColor(Color.RED)
}
R.id.green->{
//Change Background Color
backgroud.setBackgroundColor(Color.GREEN)
}
R.id.blue->{
//Change Background Color
backgroud.setBackgroundColor(Color.BLUE)
}
}
return super.onOptionsItemSelected(item)
}
}
packagecom.dharmendra.popupmenu
import android.graphics.Color
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.Button
import android.widget.PopupMenu
import android.widget.RelativeLayout
classMainActivity : AppCompatActivity() {
overridefunonCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//Find View By Id for buttonval btn = findViewById<Button>(R.id.button) as Button
//Find View By Id for Relative Layout because We need to Change It's Color.val background = findViewById<RelativeLayout>(R.id.relativeLayout) as RelativeLayout
//On Click for Button to open PopUp menu
btn.setOnClickListener {
/*Create Object Of PopupMenu we need to pas Context and View (Our View is Button so we pass btn to it) */val popUp = PopupMenu(this@MainActivity, btn)
//Inflate our menu Layout.
popUp.menuInflater.inflate(R.menu.popup_menu, popUp.menu)
//Set Click Listener on Popup Menu Item
popUp.setOnMenuItemClickListener { myItem ->
//Getting Id of selected Itemval item = myItem!!.itemId
when (item) {
R.id.red -> {
background.setBackgroundColor(Color.RED)
}
R.id.blue -> {
background.setBackgroundColor(Color.BLUE)
}
R.id.green -> {
background.setBackgroundColor(Color.GREEN)
}
}
true
}
popUp.show()
}
}
}
Go to File => New => New Project.Give Name To your application. Then, check Include Kotlin Support and click next button.
Select minimum SDK you need. However, we have selected 21 as minimum SDK. Then, click next button.
Then, select Empty Activity => click next => click finish.
2. For Custom GridView We need two XML file main xml file contain GridView and Other Contain a Single Item which we want to Show in GridView.Here we Have Two XML file
We add some Image to res/drawable to display in GridView
3. MainActivity.kt
packagecom.dharmendra.customgridview
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.GridView
import android.widget.Toast
classMainActivity : AppCompatActivity() {
overridefunonCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//Find View By Id For GridViewval gridView = findViewById<GridView>(R.id.gridView) as GridView
/*Create and ArrayList of Integer Type To Store Images From drawable.Here we add Images to ArrayList. We have Images of Android Icons of Different versions. */val arrayListImage = ArrayList<Int>()
arrayListImage.add(R.drawable.cupcake)
arrayListImage.add(R.drawable.donut)
arrayListImage.add(R.drawable.eclair)
arrayListImage.add(R.drawable.froyo)
arrayListImage.add(R.drawable.gingerbread)
arrayListImage.add(R.drawable.honeycomb)
arrayListImage.add(R.drawable.icecreamsandwich)
arrayListImage.add(R.drawable.jellybean)
arrayListImage.add(R.drawable.kitkat)
arrayListImage.add(R.drawable.lollipop)
arrayListImage.add(R.drawable.marshmallow)
arrayListImage.add(R.drawable.nougat)
arrayListImage.add(R.drawable.oreo)
// Here We take and Array of Android OS names in Same Sequence as we take Images.val name = arrayOf("Cupcake", "Donut", "Eclair", "Froyo", "Gingerbread", "Honeycomb", "Icecreamsandwich",
"Jellybean", "Kitkat", "Lollipop", "Marshmallow", "Nougat", "Oreo")
//We Have Created Custom Adapter Class in that we pass Context,ArrayList of Image and Array Of nameval customAdapter = CustomAdapter(this@MainActivity, arrayListImage, name)
//Set Adapter to ArrayList
gridView.adapter = customAdapter
//On Click for GridView Item
gridView.setOnItemClickListener { adapterView, parent, position, l ->
Toast.makeText(this@MainActivity, "Click on : " + name[position], Toast.LENGTH_LONG).show()
}
}
}
4. Now We have to Create Class CustomAdapter.Right Click on Package name---->New--->Kotlin File/Class.
Now Select Class in Kind and Add name of Class.Here Our Class name is CustomAdapter.
5. After Class is Created add parameter to Class(passed in Main Activity) and extend with BaseAdapter()
Ex:
class CustomAdapter(context: Context, arrayListImage: ArrayList<Int>, name: Array<String>
) : BaseAdapter() {
..
..
..
}
You will get Some Error Put Your Cursor on Red line And Press Alt+Enter and click on Implement Members and Select All Methods and click Ok.
CustomAdapter.kt
packagecom.dharmendra.customgridview
import android.app.Activity
import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView
import android.widget.TextView
/** * Created by root on 3/23/18. *//*We Have Created Constructor of Custom Adapter and Pass context ArrayList<Int> which Contain images Array which contain name*///Here We extend over Adapter With BaseAdapter()classCustomAdapter(context: Context, arrayListImage: ArrayList<Int>, name: Array<String>) : BaseAdapter() {
//Passing Values to Local Variablesvar context = context
var arrayListImage = arrayListImage
var name = name
//Auto Generated MethodoverridefungetView(position: Int, convertView: View?, parent: ViewGroup?): View {
var myView = convertView
var holder: ViewHolder
if (myView == null) {
//If our View is Null than we Inflater view using Layout Inflaterval mInflater = (context as Activity).layoutInflater
//Inflating our grid_item.
myView = mInflater.inflate(R.layout.grid_item, parent, false)
//Create Object of ViewHolder Class and set our View to it
holder = ViewHolder()
//Find view By Id For all our Widget taken in grid_item./*Here !! are use for non-null asserted two prevent From null. you can also use Only Safe (?.) */
holder.mImageView = myView!!.findViewById<ImageView>(R.id.imageView) as ImageView
holder.mTextView = myView!!.findViewById<TextView>(R.id.textView) as TextView
//Set A Tag to Identify our view.
myView.setTag(holder)
} else {
//If Our View in not Null than Just get View using Tag and pass to holder Object.
holder = myView.getTag() as ViewHolder
}
//Setting Image to ImageView by position
holder.mImageView!!.setImageResource(arrayListImage.get(position))
//Setting name to TextView by position
holder.mTextView!!.setText(name.get(position))
return myView
}
//Auto Generated MethodoverridefungetItem(p0: Int): Any {
return arrayListImage.get(p0)
}
//Auto Generated MethodoverridefungetItemId(p0: Int): Long {
return0
}
//Auto Generated MethodoverridefungetCount(): Int {
return arrayListImage.size
}
//Create A class To hold over View like we taken in grid_item.xmlclassViewHolder {
var mImageView: ImageView? = nullvar mTextView: TextView? = null
}
}
Go to File => New => New Project.Give Name To your application. Then, check Include Kotlin Support and click next button.
Select minimum SDK you need. However, we have selected 21 as minimum SDK. Then, click next button.
Then, select Empty Activity => click next => click finish.
2. For Custom ListView We need two XML file main xml file contain listView and Other Contain a Single ROW which we want to Show in ListView.Here we Have Two XML file
We add some Image to res/drawableto display in listView
3. MainActivity.kt
packagecom.dharmendra.customlistview
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.ListView
import android.widget.Toast
classMainActivity : AppCompatActivity() {
overridefunonCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//Find View By Id For Listviewval listview = findViewById<ListView>(R.id.listView) as ListView
/*Create and ArrayList of Integer Type To Store Images From drawable.Here we add Images to ArrayList. We have Images of Android Icons of Diffrent versions. */val image = ArrayList<Int>()
image.add(R.drawable.cupcake)
image.add(R.drawable.donut)
image.add(R.drawable.eclair)
image.add(R.drawable.froyo)
image.add(R.drawable.gingerbread)
image.add(R.drawable.honeycomb)
image.add(R.drawable.icecreamsandwich)
image.add(R.drawable.jellybean)
image.add(R.drawable.kitkat)
image.add(R.drawable.lollipop)
image.add(R.drawable.marshmallow)
image.add(R.drawable.nougat)
image.add(R.drawable.oreo)
// Here We take and Array of Android OS names in Same Sequence as we take Images.val name = arrayOf("Cupcake", "Donut", "Eclair", "Froyo", "Gingerbread", "Honeycomb", "Icecreamsandwich",
"Jellybean", "Kitkat", "Lollipop", "Marshmallow", "Nougat", "Oreo")
// Here We take and Array of Android OS Version in Same Sequence as we take Images and name.val version = arrayOf("1.5", "1.6", "2.0", "2.2", "2.3", "3.0", "4.0",
"4.1", "4.4", "5.0", "6.0", "7.0", "8.0")
/*Create ArrayList of HashMap to Store Name and Version with Key value Pair at Same poition Ex:- At Position 1: name:"Cupcake" version:"1.5" At Position 2: name:"Donut" version:"1.6" . . . So On */val info = ArrayList<HashMap<String, String>>()
//Here We take HashMap in that we add Name and Version from Arrayvar hashMap: HashMap<String, String> = HashMap<String, String>()
for (i in0..name.size - 1) {
hashMap = HashMap<String, String>()
hashMap.put("name", name[i])
hashMap.put("version", version[i])
//Add HashMap to ArrayList
info.add(hashMap)
/* ArrayList Start with Position 0 So we have At position 0: name:"Cupcake" version:"1.5" */
}
//We Have Created Custom Adapter Class in that we pass Context,Array of Image and ArrayList<Hashmap<String,String>>val customAdapter = CustomAdapter(this, image, info)
//Set Adapter to ArrayList
listview.adapter = customAdapter
//On Click for ListView Item
listview.setOnItemClickListener { adapterView, view, position, l ->
Toast.makeText(this@MainActivity, "Name : " + name[position] + "\nVersion : " + version[position], Toast.LENGTH_LONG).show()
}
}
}
4. Now We have to Create Class CustomAdapter.Right Click on Package name---->New--->Kotlin File/Class.
Now Select Class in Kind and Add name of Class.Here Our Class name is CustomAdapter.
5. After Class is Created add parameter to Class(passed in Main Activity) and extend with BaseAdapter()
You will get Some Error Put Your Cursor on Red line And Press Alt+Enter and click on Implement Members and Select All Methods and click Ok.
CustomAdapter.kt
packagecom.dharmendra.customlistview
import android.app.Activity
import android.content.Context
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView
import android.widget.TextView
/** * Created by root on 3/18/18. *//*We Have Created Constructor of Custom Adapter and Pass context ArrayList<Int> which Contain images ArrayList<HashMap<String,String>> which contain name and version*///Here We extend over Adapter With BaseAdapter()classCustomAdapter(context: Context, image: ArrayList<Int>, arrayList: ArrayList<HashMap<String, String>>) : BaseAdapter() {
//Passing Values to Local Variablesvar image = image
var arrayList = arrayList
var context = context
//Auto Generated MethodoverridefungetView(position: Int, convertView: View?, parent: ViewGroup?): View {
var myview = convertView
val holder: ViewHolder
if (convertView == null) {
//If Over View is Null than we Inflater view using Layout Inflaterval mInflater = (context as Activity).layoutInflater
//Inflating our list_row.
myview = mInflater!!.inflate(R.layout.list_row, parent, false)
//Create Object of ViewHolder Class and set our View to it
holder = ViewHolder()
//Find view By Id For all our Widget taken in list_row./*Here !! are use for non-null asserted two prevent From null. you can also use Only Safe (?.) */
holder.mImageView = myview!!.findViewById<ImageView>(R.id.imageview) as ImageView
holder.mHeader = myview!!.findViewById<TextView>(R.id.header) as TextView
holder.mSubHeader = myview!!.findViewById<TextView>(R.id.subHeader) as TextView
//Set A Tag to Identify our view.
myview.setTag(holder)
} else {
//If Ouer View in not Null than Just get View using Tag and pass to holder Object.
holder = myview!!.getTag() as ViewHolder
}
//Getting HasaMap At Perticular Positionval map = arrayList.get(position)
//Setting Image to ImageView by position
holder.mImageView!!.setImageResource(image[position])
//Setting name to TextView it's Key from HashMap At Position
holder.mHeader!!.setText(map.get("name"))
//Setting version to TextView it's Key from HashMap At Position
holder.mSubHeader!!.setText(map.get("version"))
return myview
}
//Auto Generated MethodoverridefungetItem(p0: Int): Any {
//Return the Current Position of ArrayList.return arrayList.get(p0)
}
//Auto Generated MethodoverridefungetItemId(p0: Int): Long {
return0
}
//Auto Generated MethodoverridefungetCount(): Int {
//Return Size Of ArrayListreturn arrayList.size
}
//Create A class To hold over View like we taken in list_row.xmlclassViewHolder {
var mImageView: ImageView? = nullvar mHeader: TextView? = nullvar mSubHeader: TextView? = null
}
}