Saturday 14 July 2018

HB Blog 157: Listview In Android Using Kotlin.

Kotlin is now an official language on Android. It's expressive, concise, and powerful. Best of all, it's interoperable with our existing Android languages and runtime.

Basically, it is not very hard to write a code in Kotlin language but, we need to start from class day 1.
Lets say, for getting started in kotlin you can refer link, Get Started with Kotlin on Android
There are few syntax to be adopted and file format as .kt instead of .java.

In this tutorial, I will show how to create a listview with custom adapter in Kotlin Android Application,
Refer the below link for complete sample code:-

Download Sample Code

Have a look on few code snippets,

//MainActivity.kt
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package com.harshalbenake.koltinlist

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.EditText
import android.widget.ListView
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*

/**
 * Main Activity
 */
class MainActivity : AppCompatActivity() {
    //array variable initialized
    var listItems = arrayListOf()
    //listview initialized
    private lateinit var lv_nameslist: ListView

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

        //smartcast - textview appearance changed without findViewById
        tv_name.text = "Enter name for adding to list"
        tv_name.setTextColor(Color.parseColor("#006500"))
        tv_name.textSize = 20F

        //editext variable using findViewById
        val et_name = findViewById(R.id.et_name)

        lv_nameslist = findViewById(R.id.lv_nameslist)

        //arraylist item added
        listItems.add("harshalbenake1")
        listItems.add("harshalbenake2")
        listItems.add("harshalbenake3")

        //variable value initialized and added to list
        var newName = "harshalbenake4"
        newName = "harshalbenake5"
        listItems.add(newName)

        //adapter set
        setAdapter(listItems)

        //button onclick event
        bt_add.setOnClickListener() {
            //methods called to add name
            addName("harshalbenake6")
            addName(et_name.text.toString())
        }

        //listview onitemclick event
        lv_nameslist.setOnItemClickListener { parent, view, position, id ->
            //item value retrived from positon
            var strName = parent.getItemAtPosition(position) as String
            //toast display
            Toast.makeText(this,strName,Toast.LENGTH_SHORT).show()
            //data passed to another activity
            val intent=Intent(this,DetailActivity::class.java)
            intent.putExtra("strNamePass", strName)
            startActivity(intent);
        }

    }

    override fun onPause() {
        super.onPause()
        //lifecycle method override
        println("onPause called")
    }

    /**
     * add Name
     */
    fun addName(strString: String) {
        //empty value check
        if(strString!="") {
            listItems.add(strString)
            setAdapter(listItems)
        }else{
            Toast.makeText(this,"No Name Added",Toast.LENGTH_SHORT).show()
        }
    }

    /**
     * set Adapter
     */
    fun setAdapter(items: ArrayList) {
        //CustomBaseAdapter class parameterized constructor called
        var adapter = CustomBaseAdapter(items, this)
        //adapter set to listview
        lv_nameslist.adapter = adapter
    }
}

//CustomBaseAdapter.kt
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package com.harshalbenake.koltinlist

import android.content.Context
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.TextView

/**
 * Custom Base Adapter
 */
class CustomBaseAdapter(list: ArrayList, context: Context) : BaseAdapter() {
    //LayoutInflater initialized
    val mInflater: LayoutInflater = LayoutInflater.from(context)
    //list passed from mainactivity copyied to locallist
    var localList = list

    override fun getCount(): Int {
        return localList.size
    }

    override fun getItem(position: Int): Any {
        return localList[position]
    }

    override fun getItemId(position: Int): Long {
        return position.toLong()
    }

    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View? {
        val view: View?
        val viewHolder: ViewHolder
        if (convertView == null) {
            view = mInflater.inflate(R.layout.rowitem_name, parent, false)
            viewHolder = ViewHolder(view)
            view?.tag = viewHolder
        } else {
            view = convertView
            viewHolder = view.tag as ViewHolder
        }

        viewHolder.tv_rowitemname.setTextColor(Color.parseColor("#654657"))
        viewHolder.tv_rowitemname.textSize = 20F
        viewHolder.tv_rowitemname.text = localList.get(position).toString()
        return view
    }

    /**
     * View Holder class
     */
    private class ViewHolder(row: View) {
        var tv_rowitemname: TextView
        //view initialized using findViewById
        init {
            this.tv_rowitemname = row.findViewById(R.id.tv_rowitemname)
        }
    }
}

//DetailActivity.kt
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
package com.harshalbenake.koltinlist

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_detail.*

/**
 * Detail Activity class
 */
class DetailActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_detail)
        //intent data extracted
        var strName= intent.getStringExtra("strNamePass")
        tv_detailname.text=strName
    }
}