How to create GridView Layout in an Android App using Kotlin?

Kotlin AndroidApps/ApplicationsMobile Development

This example demonstrates how to create GridView Layout in an Android App using Kotlin.

Step 1 − Create a new project in Android Studio, go to File? New Project and fill all required details to create a new project.

Step 2 − Add the following code to res/layout/activity_main.xml.

Example

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
   tools:context=".MainActivity">
<GridView
   android:id="@+id/gridView"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:numColumns="2" />
</RelativeLayout>

Step 3 − Add the following code to src/MainActivity.kt

import android.os.Bundle
import android.widget.AdapterView.OnItemClickListener
import android.widget.GridView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
   lateinit var gridView: GridView
   private var playerNames = arrayOf("Cristiano Ronaldo", "Joao Felix", "Bernado Silva", "Andre    Silve", "Bruno
   Fernandez", "William Carvalho", "Nelson Semedo", "Pepe", "Rui Patricio")
   private var playerImages = intArrayOf(R.drawable.ronaldo, R.drawable.felix, R.drawable.bernado,
   R.drawable.andre,
   R.drawable.bruno, R.drawable.carvalho, R.drawable.semedo, R.drawable.pepe, R.drawable.patricio)
   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
      title = "KotlinApp"
      gridView = findViewById(R.id.gridView)
      val mainAdapter = MainAdapter(this@MainActivity, playerNames, playerImages)
      gridView.adapter = mainAdapter
      gridView.onItemClickListener = OnItemClickListener { _, _, position, _ ->
         Toast.makeText(applicationContext, "You CLicked " + playerNames[+position],
         Toast.LENGTH_SHORT).show()
      }
   }
}

Step 4 − Create a Kotlin class (MyAdapter.kt) and add the following code

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView
import android.widget.TextView
internal class MainAdapter(
   private val context: Context,
   private val numbersInWords: Array<String>,
   private val numberImage: IntArray
) :
BaseAdapter() {
   private var layoutInflater: LayoutInflater? = null
   private lateinit var imageView: ImageView
   private lateinit var textView: TextView
   override fun getCount(): Int {
      return numbersInWords.size
   }
   override fun getItem(position: Int): Any? {
      return null
   }
   override fun getItemId(position: Int): Long {
      return 0
   }
   override fun getView(
   position: Int,
   convertView: View?,
   parent: ViewGroup
   ): View? {
      var convertView = convertView
      if (layoutInflater == null) {
         layoutInflater =
         context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
      }
      if (convertView == null) {
         convertView = layoutInflater!!.inflate(R.layout.rowitem, null)
      }
      imageView = convertView!!.findViewById(R.id.imageView)
      textView = convertView.findViewById(R.id.textView)
      imageView.setImageResource(numberImage[position])
      textView.text = numbersInWords[position]
      return convertView
   }
}

Step 5 − Create a Layout Resource file (row_item.xml) and add the following code −

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:orientation="vertical"
   android:gravity="center"
   android:padding="8dp">
<ImageView
   android:id="@+id/imageView"
   android:layout_width="100dp"
   android:layout_height="100dp" />
<TextView
   android:textAlignment="center"
   android:gravity="center"
   android:id="@+id/textView"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_marginTop="16dp"
   android:text="Numbers"
   android:layout_marginBottom="10dp"
   android:textColor="@android:color/background_dark"
   android:textSize="24sp"
   android:textStyle="bold" />
</LinearLayout>

Step 6 − Add the following code to androidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.q11">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>

Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen


raja
Published on 21-Jul-2020 12:01:14
Advertisements