यह उदाहरण दर्शाता है कि Kotlin में setOnItemClickListener का उपयोग करके ListView आइटम क्लिक इवेंट को कैसे संभाला जाए।
चरण 1 - नया प्रोजेक्ट बनाएं
Android Studio: File → New Project।
चरण 2 - activity_main.xml लेआउट
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:id="@+id/rl"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="सबसे अच्छा फुटबॉल खिलाड़ी कौन है?"
android:textColor="@android:color/holo_purple"
android:textStyle="italic|bold" />
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/textView" />
</RelativeLayout>
चरण 3 - MainActivity.kt में क्लिक लिस्टनर
import android.os.Bundle
import android.widget.ArrayAdapter
import android.widget.ListView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
val listView = findViewById<ListView>(R.id.listView)
val textView = findViewById<TextView>(R.id.textView)
val players = arrayOf(
"Cristiano Ronaldo", "Messi", "Pele",
"Ronaldinho", "Maradona", "Neymar"
)
val adapter = ArrayAdapter(
this,
android.R.layout.simple_list_item_1,
players
)
listView.adapter = adapter
listView.setOnItemClickListener { parent, _, position, _ ->
val selectedPlayer = parent.getItemAtPosition(position) as String
textView.text = "सबसे अच्छा फुटबॉल खिलाड़ी है: $selectedPlayer"
}
}
}
चरण 4 - AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.example.listviewclick">
<application ...>
<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>
ऐप चलाएं
ऐप चलाएं। सूची में किसी खिलाड़ी के नाम पर टैप करें। शीर्ष का टेक्स्ट बदलकर चयनित खिलाड़ी का नाम दिखाएगा।
आधुनिक विकल्प: नए ऐप्स के लिएListViewके बजायRecyclerViewका उपयोग करने की सलाह दी जाती है। RecyclerView मेंOnClickListenerको एडाप्टर केonBindViewHolderमें सेट किया जाता है।