Simple clickable Android ListView example



Follow this short tutorial to create a ListView in Android.

First let’s create the list view element in our layout file:

<ListView
android:id="@+id/lblistview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

Then in your Java file:

lblist = (ListView)findViewById(R.id.lblistview);

String[] items = new String[3];
items[0] = "First item";
items[1] = "Second item";
items[2] = "Third item";

ArrayAdapter<String> lbadapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, items);

lblist.setAdapter(lbadapter);

lblist.setOnItemClickListener(new AdapterView.OnItemClickListener() {

	@Override
	public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {
		final String item = (String) parent.getItemAtPosition(position);
		Toast.makeText(getApplicationContext(),item, Toast.LENGTH_LONG).show();
	}

});

By clicking on each item a toast message will be displayed containing item text.

loading...

Leave a Reply

Your email address will not be published. Required fields are marked *