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
- main_activity.xml
- 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:
This blog gives very important information ,Thanks for sharing
ReplyDeleteAndroid Online Course
Thank you very much mounika
Deletethanks for this tutorial, can you add a searchview for gridview?
ReplyDeleteNot much change in search view for grid and list you can try it by your self. Still i will try to upload as soon as possible.
DeleteWow, hah. That's probably the easiest and most coherent tutorial I've seen for android. Took me 5 mins to get it working and i was breaking my head on similar tutorial for half an hour before that. Thx
ReplyDeleteThank you
ReplyDelete