By Alvin Alexander. Last updated: August 29, 2017
This source code shows a simple example of how to create an Android ListActivity
and ListView
, using a static array of elements for the list. While the Android RecyclerView is generally preferred over the older ListActivity/ListView approach, the older approach is easy to implement, and still works fine in some situations.
My ListActivity class
package com.devdaily.android.twitterclient; import android.app.ListActivity; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; public class TwitterClient extends ListActivity { String[] values = { "Stream", "My Lists", "My Searches", "Trends" }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.mainmenu); // parameters are (Context, layout for the row, and the array of data) setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, values)); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { String item = (String) getListAdapter().getItem(position); Toast.makeText(this, item + " selected", Toast.LENGTH_LONG).show(); } }
My mainmenu.xml file that declares a ListView
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <ListView android:id="@android:id/list" android:layout_width="match_parent" android:layout_height="wrap_content" > </ListView> </LinearLayout>