Friday, 30 March 2018

Context Menu Using Kotlin in Android



1. Creating New Project in Kotlin
  • Open Android Studio.
  • 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.Which Contain ListView.We Have to Perform Long Click on ListView Item to open Context Menu.

activity_main.xml

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

    <TextView
        android: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" />

    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>


3.MainActivity.kt


package com.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


class MainActivity : AppCompatActivity() {

    lateinit var array: Array<String>

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

        //Find View By Id For ListView
        val 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 Adapter
        val 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)

    }

    override fun onCreateContextMenu(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
         */

    }

    override fun onContextItemSelected(item: MenuItem?): Boolean {

        //Get Order of Selected Item
        val selectedItemOrder = item!!.order

        //Get Title Of Selected Item
        val selectedItemTitle = item.title


        //To get Name of Person Click on ListView
        val info = item.menuInfo as AdapterContextMenuInfo
        val listPosition = info.position
        val name = array[listPosition]
        
        Toast.makeText(this@MainActivity, " " + selectedItemTitle + " " + name, Toast.LENGTH_LONG).show()
        
        return true
    }
}

Output:


Tuesday, 27 March 2018

Option Menu Using Kotlin in Android



1. Creating New Project in Kotlin
  • Open Android Studio.
  • 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"?>
<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"
    android:id="@+id/relative"
    tools:context="com.dharmendra.optionmenu.MainActivity">

    <TextView
        android: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.


option_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">


    <item
        android:id="@+id/magenta"
        android:title="Magenta" />
    <item
        android:id="@+id/yellow"
        android:title="Yellow" />


    <item
        android:id="@+id/red"
        android:title="Red" />
    <item
        android:id="@+id/blue"
        android:title="Blue" />
    <item
        android:id="@+id/green"
        android:title="green" />


</menu>


Right Click on menu folder. New->menu resource file provide name to file and click Ok.
option_menu.xml file contain options which we want to provide.



4.MainActivity.kt


package com.dharmendra.optionmenu

import android.graphics.Color
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.RelativeLayout
import android.widget.TextView


 class MainActivity : AppCompatActivity() {

    //Define Objecct Of RelativeLayout
     lateinit var backgroud:RelativeLayout
   // 
Define Objecct Of TextView
     lateinit var textView:TextView

    override fun onCreate(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
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {

        //Inflate menu
        menuInflater.inflate(R.menu.option_menu,menu)
        return true
    }

    //Method to Handle Option Item Click

    override fun onOptionsItemSelected(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)
    }
}

Output:


Sunday, 25 March 2018

PopUp Menu Using Kotlin in Android



1. Creating New Project in Kotlin
  • Open Android Studio.
  • 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.In that we take one Button In side Relative layout.

activity_main.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"
    android:id="@+id/relativeLayout"
    tools:context="com.dharmendra.popupmenu.MainActivity">


    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Click" />
</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 popup_menu.xml


Right Click on menu folder. New->menu resource file provide name to file and click Ok.
popup_menu.xml file contain options which we want to provide. 

popup_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:id="@+id/red"
        android:title="Red" />

    <item
        android:id="@+id/blue"
        android:title="Blue" />

    <item
        android:id="@+id/green"
        android:title="Green" />


</menu>


4.MainActivity.kt


package com.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

class MainActivity : AppCompatActivity() {

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

        //Find View By Id for button
        val 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 Item
                val 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()


        }
    }
}

Output:



Friday, 23 March 2018

Android Custom GridView Example Using Kotlin


1. Creating New Project in Kotlin
  • Open Android Studio.
  • 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
  1. main_activity.xml
  2. grid_item.xml
main_activity.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="com.dharmendra.customgridview.MainActivity">

   <GridView
       android:id="@+id/gridView"
       android:numColumns="2"
       android:layout_width="match_parent"
       android:layout_height="match_parent"/>
</RelativeLayout>


grid_item.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"
    android:layout_width="match_parent" android:layout_height="match_parent">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginStart="28dp"
        android:layout_marginTop="26dp"/>

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignEnd="@+id/imageView"
        android:layout_alignStart="@+id/imageView"
        android:layout_below="@+id/imageView"
        android:layout_centerVertical="true"
        android:layout_marginTop="11dp"
        android:gravity="center"
        android:layout_centerHorizontal="true"
        android:textColor="@android:color/black"
        android:textSize="16sp" />
</RelativeLayout>


We add some Image to res/drawable to display in GridView














3. MainActivity.kt

package com.dharmendra.customgridview

import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.GridView
import android.widget.Toast

class MainActivity : AppCompatActivity() {

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

        //Find View By Id For GridView
        val 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 name

        val 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


package com.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()


class CustomAdapter(context: Context, arrayListImage: ArrayList<Int>, name: Array<String>) : BaseAdapter() {

    //Passing Values to Local Variables

    var context = context
    var arrayListImage = arrayListImage
    var name = name


    //Auto Generated Method
    override fun getView(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 Inflater

            val 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 Method
    override fun getItem(p0: Int): Any {
        return arrayListImage.get(p0)
    }

    //Auto Generated Method
    override fun getItemId(p0: Int): Long {
        return 0
    }

    //Auto Generated Method
    override fun getCount(): Int {
        return arrayListImage.size
    }


    //Create A class To hold over View like we taken in grid_item.xml

    class ViewHolder {

        var mImageView: ImageView? = null
        var mTextView: TextView? = null

    }

}

Output:

Monday, 19 March 2018

Android Custom ListView Example Using Kotlin



1. Creating New Project in Kotlin
  •  Open Android Studio.
  • 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
  1. main_activity.xml
  2. list_row.xml
main_activity.xml
<?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:orientation="vertical"
    tools:context="com.dharmendra.customlistview.MainActivity">

   <ListView
       android:id="@+id/listView"
       android:divider="@android:color/black"
       android:dividerHeight="1dp"
       android:layout_width="match_parent"
       android:layout_height="match_parent"/>

</LinearLayout>

list_row.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/imageview"
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginStart="16dp"
        android:layout_marginTop="12dp"/>

    <TextView
        android:id="@+id/header"
        android:textSize="16sp"
        android:textColor="@color/colorPrimary"
        android:textStyle="bold"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/imageview"
        android:layout_marginStart="18dp"
        android:layout_marginTop="13dp"
        android:layout_toEndOf="@+id/imageview" />

    <TextView
        android:id="@+id/subHeader"
        android:textSize="12sp"
        android:textStyle="bold"
        android:textColor="@android:color/black"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignStart="@+id/header"
        android:layout_below="@+id/header" />

</RelativeLayout>


We add some Image to res/drawable to display in listView














3. MainActivity.kt

package com.dharmendra.customlistview

import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.ListView
import android.widget.Toast

class MainActivity : AppCompatActivity() {


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

        //Find View By Id For Listview
        val 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 Array
        var hashMap: HashMap<String, String> = HashMap<String, String>()

        for (i in 0..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()

Ex:
class CustomAdapter(context: Context, image: ArrayList<Int>, arrayList: ArrayList<HashMap<String, 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



package com.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()

class CustomAdapter(context: Context, image: ArrayList<Int>, arrayList: ArrayList<HashMap<String, String>>) : BaseAdapter() {

    //Passing Values to Local Variables
    var image = image
    var arrayList = arrayList
    var context = context


    //Auto Generated Method
    override fun getView(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 Inflater
            val 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 Position
        val 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 Method
    override fun getItem(p0: Int): Any {

        //Return the Current Position of ArrayList.
        return arrayList.get(p0)

    }

    //Auto Generated Method
    override fun getItemId(p0: Int): Long {
        return 0
    }

    //Auto Generated Method

    override fun getCount(): Int {

        //Return Size Of ArrayList
        return arrayList.size
    }


    //Create A class To hold over View like we taken in list_row.xml
    class ViewHolder {

        var mImageView: ImageView? = null
        var mHeader: TextView? = null
        var mSubHeader: TextView? = null
    }
}

Output: