Wednesday 4 April 2018

SearchView in ListView with a custom Adapter 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. For Search in Custom ListView We need two XML file main xml file contain listView and SearchView.
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:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">


    <SearchView
        android:id="@+id/searchView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</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.searchview

import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.ListView
import android.widget.SearchView
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(R.id.listView) as ListView

        //Find View By Id For SearchView
        val searchView = findViewById(R.id.searchView) as SearchView

        /*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 ->

            //Provide the data on Click position in our listview
            val hashMap: HashMap<String, String> = customAdapter.getItem(position) as HashMap<String, String>

            Toast.makeText(this@MainActivity, "Name : " + hashMap.get("name") + "\nVersion : " + hashMap.get("version"), Toast.LENGTH_LONG).show()
        }

        searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
            override fun onQueryTextSubmit(query: String?): Boolean {
                return false
            }

            override fun onQueryTextChange(newText: String?): Boolean {

                val text = newText
                /*Call filter Method Created in Custom Adapter
                    This Method Filter ListView According to Search Keyword
                 */
                customAdapter.filter(text)
                return false
            }
        })

    }

}


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.searchview

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
import java.util.*
import kotlin.collections.ArrayList

/*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

    //Store image and arraylist in Temp Array List we Required it later
    var tempArrayList = ArrayList(image)
    var tempNameVersionList = ArrayList(arrayList)


    //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
    }


    //Function to set data according to Search Keyword in ListView
    fun filter(text: String?) {


        //Our Search text
        val text = text!!.toLowerCase(Locale.getDefault())


        //Here We Clear Both ArrayList because We update according to Search query.
        image.clear()
        arrayList.clear()


        if (text.length == 0) {

            /*If Search query is Empty than we add all temp data into our main ArrayList

            We store Value in temp in Starting of Program.

            */

            image.addAll(tempArrayList)
            arrayList.addAll(tempNameVersionList)


        } else {


            for (i in 0..tempNameVersionList.size - 1) {

                /*
                If our Search query is not empty than we Check Our search keyword in Temp ArrayList.
                if our Search Keyword in Temp ArrayList than we add to our Main ArrayList
                */

                if (tempNameVersionList.get(i).get("name")!!.toLowerCase(Locale.getDefault()).contains(text)) {

                    image.add(tempArrayList.get(i))
                    arrayList.add(tempNameVersionList.get(i))


                }

            }
        }

        //This is to notify that data change in Adapter and Reflect the changes.
        notifyDataSetChanged()


    }


}


Output:



No comments:

Post a Comment