A Listview Android is an adapter view that does not know the details, such as type and contents, of the views it contains. Instead list view requests views on demand from a ListAdapter as needed, such as to display new views as the user scrolls up or down.
class MainActivity : AppCompatActivity() {activity_main.xml
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val list = mutableListOf(
"African violet",
"Alloy orange",
"Amaranth pink",
"Apple green",
"Beau blue",
"Black chocolate"
)
val adapter = ArrayAdapter<String>(
this,
android.R.layout.simple_list_item_1,list
)
listView.adapter = adapter
listView.onItemClickListener = OnItemClickListener {
parent, view, position, id ->
val selectedItemText = parent.getItemAtPosition(position)
textView.text = "Selected : $selectedItemText"
}
}
}
<?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:id="@+id/constraintLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<com.google.android.material.textview.MaterialTextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:textAppearance=
"@style/TextAppearance.MaterialComponents.Subtitle1"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
tools:text="TextView" />
</androidx.constraintlayout.widget.ConstraintLayout>
No comments:
Post a Comment