Skip to main content

Simplify Your Tax Calculations with GST Calculator 2024: The Ultimate Tool for Businesses and Individuals

SearchView in Android with RecyclerView | Toolbar | Kotlin

 The search functionality in android App is a very important feature of any list page. In this article I make a simple android application to describe the SearchView integration in Android with RecyclerView | Toolbar | Kotlin.


Follow the steps-

Step 1 : 

First create a blank project in android studio with simple empty activity.









Step 2 : 

Use the below code in colors.xml file

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="purple_200">#FFBB86FC</color>
    <color name="purple_500">#FF6200EE</color>
    <color name="purple_700">#FF3700B3</color>
    <color name="teal_200">#FF03DAC5</color>
    <color name="teal_700">#FF018786</color>
    <color name="black">#FF000000</color>
    <color name="white">#FFFFFFFF</color>
</resources>

Step 3: 

themes.xml

<resources>
    <!-- Base application theme. -->
    <style name="Theme.SearchViewExample" parent="Theme.MaterialComponents.DayNight.NoActionBar">
        <!-- Primary brand color. -->
        <item name="colorPrimary">@color/purple_500</item>
        <item name="colorPrimaryVariant">@color/purple_700</item>
        <item name="colorOnPrimary">@color/white</item>
        <!-- Secondary brand color. -->
        <item name="colorSecondary">@color/teal_200</item>
        <item name="colorSecondaryVariant">@color/teal_700</item>
        <item name="colorOnSecondary">@color/black</item>
        <!-- Status bar color. -->
        <item name="android:statusBarColor" >?attr/colorPrimaryVariant</item>
        <!-- Customize your theme here. -->
    </style>

    <style name="toolBarWhite" parent="ThemeOverlay.AppCompat.Dark.ActionBar">
        <item name="android:textColorPrimary">@android:color/white</item>
        <item name="android:textColorSecondary">@android:color/white</item>
    </style>

    <style name="Toolbar.TitleText" parent="TextAppearance.Widget.AppCompat.Toolbar.Title">
        <item name="android:textSize">14sp</item>
        <item name="android:textStyle">normal</item>
    </style>
</resources>


Step 4: 

Take a image from android vector asset name of ic_baseline_search_24


Step 5 : 

create a android resource directory name of menu


after clicking on OK button a new folder will be created inside of res folder with name on menu.

Step 6: 

Now create a xml file inside of menu folder name of menu_search.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/appSearchBar"
        android:icon="@drawable/ic_baseline_search_24"
        android:title="Search..."
        app:actionViewClass="androidx.appcompat.widget.SearchView"
        app:showAsAction="always|withText" />

</menu>

Step 7:

Now design the list item xml file inside res/layout folder  name of row_view.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="5dp">

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="15dp"
        android:text="@string/app_name"
        android:textColor="@color/black"
        android:textSize="18sp" />
</androidx.cardview.widget.CardView>

 

Step 8:

Now design the activity_main.xml file

<?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=".MainActivity">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/teal_200"
        android:theme="@style/toolBarWhite"
        app:layout_constraintTop_toTopOf="parent"
        app:menu="@menu/menu_search"
        app:title="SearchView Example"
        app:titleTextAppearance="@style/Toolbar.TitleText" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toBottomOf="@id/toolBar"
        tools:listitem="@layout/row_view" />

</androidx.constraintlayout.widget.ConstraintLayout>


Step 9:

Now add the kotlin-android-extensions plugin in build.gradle

plugins {
    id 'com.android.application'
    id 'org.jetbrains.kotlin.android'
    id 'kotlin-android-extensions'
}

android {
    compileSdk 32

    defaultConfig {
        applicationId "com.example.searchview"
        minSdk 24
        targetSdk 32
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
}

dependencies {

    implementation 'androidx.core:core-ktx:1.8.0'
    implementation 'androidx.appcompat:appcompat:1.4.2'
    implementation 'com.google.android.material:material:1.6.1'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}


Step 10: 

now write the code of RecyclerView Adapter name of SearchAdapter.kt

package com.example.searchview

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.row_view.view.*


class SearchAdapter(
    private val list: ArrayList<String>
) :
    RecyclerView.Adapter<SearchAdapter.ViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val v = LayoutInflater.from(parent.context)
            .inflate(R.layout.row_view, parent, false)
        return ViewHolder(v)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bindItems(list[position])


    }

    override fun getItemCount(): Int {
        return list.size
    }


    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

        fun bindItems(item: String) {


            itemView.textView.text = item
        }
    }


}

Step 11: 

now write the code of MainActivity.kt

package com.example.searchview

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.Menu
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.SearchView
import androidx.recyclerview.widget.LinearLayoutManager
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity(), SearchView.OnQueryTextListener {
    private var searchView: SearchView? = null
    private val listLanguages = ArrayList<String>()
    private val listFilter = ArrayList<String>()
    private val adapterSearch = SearchAdapter(listFilter)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        setSupportActionBar(toolBar)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        supportActionBar?.setDisplayShowHomeEnabled(true)


        listLanguages.add("Android")
        listLanguages.add("iOS")
        listLanguages.add("Spring")
        listLanguages.add("Java")
        listLanguages.add("PHP")
        listLanguages.add("Html")
        listLanguages.add("css")
        listLanguages.add("JavaScript")
        listLanguages.add("Python")
        listLanguages.add("Laravel")
        listLanguages.add("Django")
        listLanguages.add("React JS")

        listFilter.addAll(listLanguages)

        recyclerView.apply {
            layoutManager = LinearLayoutManager(context)
            adapter = adapterSearch
        }

    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu_search, menu)

        val search = menu?.findItem(R.id.appSearchBar)
        searchView = search?.actionView as? SearchView

        searchView?.setOnQueryTextListener(this)

        return super.onCreateOptionsMenu(menu)
    }

    override fun onQueryTextSubmit(query: String?): Boolean {

        println("I am in onQueryTextSubmit: $query")
        return true
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun onQueryTextChange(newText: String?): Boolean {

        println("I am in onQueryTextChange: $newText")

        listFilter.apply {
            clear()
            addAll(listLanguages.filter { s ->
                s.lowercase().startsWith(newText?.lowercase()!!)
            })
        }


        println("I am size: ${listFilter.size}")
        adapterSearch.notifyDataSetChanged()



        return true
    }
}

Step 12:

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.example.searchview">

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.SearchViewExample"
        tools:targetApi="31">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

 

Now Simply run the project and see the result.







Happy Coding......


Download the full Source code from here-











Comments

Post a Comment

Popular posts from this blog

How to Insert Multiple rows in a single db transaction in Android Room Database? | Android | Room DB

  To insert multiple rows into a Room database in Android, you can follow these steps: 1. Set up Room Database: First, make sure you have set up your Room database correctly in your Android project. Define your Entity class, create a Database class that extends RoomDatabase, and set up your DAO (Data Access Object) interface. 2. Create Entity Class: Define an Entity class that represents the data you want to insert into the database. For example: 1 2 3 4 5 6 7 8 9 @Entity (tableName = "my_table" ) public class MyEntity { @PrimaryKey (autoGenerate = true ) public int id; public String name; public int age; // Add other fields and getters/setters as needed } Create DAO: Create a DAO interface with a method to insert multiple rows. For example: 1 2 3 4 5 @Dao public interface MyEntityDao { @Insert void insertAll (List<MyEntity> entities); } Initialise Database and DAO: In your application code, create an insta

How to fetch Latitude, Longitude from address and vice-versa(address from Latitude, Longitude) using Google Geo coder SDK in android| Kotlin

 In this Android development related article, you will get a simple solution that, how to get address using Latitude, Longitude and vice-versa. i.e latitude, longitude from an address text. It is very easy and simple. Read full article and carefully follow all the steps. Here we use google Geocoder SDK. Okay, first we create an android project in kotlin and create an Activity say MainActivity.kt. Use the below code- Function get Latitude, Longitude from Address- fun getLatLngFromAddress (context: Context, mAddress: String): String { val coder = Geocoder(context) lateinit var address: List<Address> try { address = coder.getFromLocationName(mAddress, 5 ) if (address == null ) { return "Fail to find Lat,Lng" } val location = address[ 0 ] return " Latitude: ${location.latitude}\n Longitude: ${location.longitude}" } catch (e: Exception

Recycler View Like Google Play Store App | How to use SnapHelper Android, Kotlin

 If we see the google play store android app, we can see that the app list in horizontal recycler view hold a property that the first property hold always full visible or not visible, but a portion visible is not seeing. This property is snap property. In this article I show you how to use it in our own application. Basically we use two type of snap. Center Snap and start snap. I show you both here. So read full article here. The Key Moment code is here- For center snap you need to write 2 lines code- //center Snap val snapHelper = LinearSnapHelper() snapHelper.attachToRecyclerView(recyclerView1) For start snap, create a class in kotlin say StartSnapHelper.kt package com.example.snaphelpersampleapp import android.view.View import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.LinearSnapHelper import androidx.recyclerview.widget.OrientationHelper import androidx.recyclerview.widget.RecyclerView class StartSnapHelpe