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 take GridView in our layout and set numColumns=3.It means 3 Columns in View. As in below xml layout.
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.gridview.MainActivity"> <GridView android:id="@+id/gridView" android:numColumns="3" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout>
3.MainActivity.kt
package com.dharmendra.gridview import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.widget.ArrayAdapter 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 //Define ArrayList var arrayList = ArrayList<Int>() //While Loop to Insert value in ArrayList var i = 0 while (i <= 20) { arrayList.add(i) i++ } //Create Adapter val myAdapter: ArrayAdapter<Int> = ArrayAdapter(this@MainActivity, android.R.layout.simple_list_item_1, arrayList) //Set Adapter gridView.adapter = myAdapter //GridView On Click gridView.setOnItemClickListener { adapterView, view, position, id -> Toast.makeText(this@MainActivity, "You have Click " + arrayList.get(position), Toast.LENGTH_LONG).show() } } }
Output:
No comments:
Post a Comment