Using ListView
Posted on Wednesday, July 10, 2013
How to implement a ListView.
What for?
If you want to show a scrollable list of elements you should implement a ListView control. This is a tricky control, so we’ll see how to use it.We want to show an option list like this:Resources
First thing, we must define the needed resources, so, in res/values/strings.xml we’ll create all names needed to show.You need to fill the listview in runtime, so you’ll do this programmatically.There are different ways to do it. Now we’ll see an easy method. In coming posts we’ll see other implementations.
<string name="menu_play">Play</string><string name="menu_settings">Settings</string><string name="menu_help">Help</string><string name="menu_statistics">Statistics</string>
Method 1: Create an activity that extends ListActivity
ListActivity is a class that displays a scrollable list of items and provides callback methods when the user selects one item. So, if your activity extends this class you have most of the hard work done.You need a place to save the data to show, and also an adapter, that connects the data with the ListView object. We have some standard adapters, as for example ArrayAdapter and CursorAdapter.A simple way to store your data is to have an array of strings that contains the labels you’re going to show. In this case you should use the ArrayAdapter.1- Without a specific layout
If you do not assign a specific layout for your activity, the activity will show the default one. So, if you don’t need in your layout anything different from the ListView, this is a good option and the easiest one.Be aware: you don’t have to use the setContentView() because you don’t have a specific layout
Note that in this simple method you use the predefined textview R.layout.simple_list_item_1.The result is this:
public class MenuPrincipalActivity extends ListActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);// here you create an array with your labelsString[] items = {getString(R.string.menu_play),getString(R.string.menu_settings),getString(R.string.menu_help),getString(R.string.menu_statistics),};//and now use an adapter to connect the label string and the listviewArrayAdapter<String> adapt = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,items);setListAdapter(adapt);}
2- Using a specific layout
If you want to assign a specific layout for your activity, this layout must contain a ListView with the android:id attribute set to @android:id/list. And you also must to assign the layout to the activity via setContentView(), as always.For example, the layout code could be:<LinearLayout 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"android:orientation="vertical"android:background="@color/fondo_pesonalizado"android:paddingLeft="@dimen/activity_horizontal_margin"android:paddingRight="@dimen/activity_horizontal_margin"android:paddingTop="@dimen/activity_vertical_margin"android:paddingBottom="@dimen/activity_vertical_margin"tools:context=".MenuPrincipalActivity"><TextViewandroid:layout_width="fill_parent"android:layout_height="wrap_content"android:text="@string/menu_subtitulo"android:id="@+id/menu_titulo"android:layout_margin="@dimen/dimension_minima"android:editable="false"android:textAlignment="center"android:textStyle="italic"android:textColor="@android:color/tertiary_text_light"android:gravity="center"/><ListViewandroid:layout_width="fill_parent"android:layout_height="fill_parent"android:id="@android:id/list"android:layout_gravity="left|center_vertical"android:divider="@android:drawable/divider_horizontal_textfield"android:footerDividersEnabled="false"/></LinearLayout>
And the activity:
public class MenuPrincipalActivity extends ListActivity {And the result is:
@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_menu_principal);// here you create an array with your labelsString[] items = {getString(R.string.menu_play),getString(R.string.menu_settings),getString(R.string.menu_help),getString(R.string.menu_statistics),};//and now use an adapter to connect the label string and the listviewArrayAdapter<String> adapt = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,items);setListAdapter(adapt);}
3- Using a specific background layout and item layout
If you want to use a specific view for each item instead an android default TextView, act as follows:Create an item layout, for example like this:<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"android:layout_width="match_parent"android:layout_height="match_parent"><ImageViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:id="@+id/icono"android:src="@android:drawable/btn_star"android:layout_alignParentTop="true"android:layout_alignParentLeft="true"/><TextViewandroid:layout_width="wrap_content"android:layout_height="fill_parent"android:text="New Text"android:id="@+id/texto_item"android:textSize="@dimen/texto_menu"/></LinearLayout>
and now, change the abobe adapter by this one:
ArrayAdapter<String> adapt = new ArrayAdapter<String>(this,R.layout.menu_item,R.id.texto_item,items);where:
- menu_item is the specific layout that you have created for your item
- texto_item is the TextView that you use in the menu_item layout to show the item text
- items is the array that contains the texts to show.
4ยบ. Create your own adaptator
If you want to customize your item view with other features, for example different icons, you’ll need to create your own adapter.You must create a new class that extends BaseAdapter. This class must overwrite four methods:
- View getView(int position, View convertView, ViewGroup parent). This method builds and returns a new View object with the corresponding position. Optionally we can start from a convertview view to generate faster views.
- int getCount(). Returns the number of elements in the list.
- Object getItem(int position). Returns data item associated with thespecified position in the data set..
- long getItemId(int position). Returns the row id associated with the specified position in the list
And in the activity:
public class MiAdaptador extends BaseAdapter {private final Activity actividad;private final Vector<String> lista;public MiAdaptador(Activity actividad, Vector<String> lista) {super();this.actividad = actividad;this.lista = lista;}public View getView(int position, View convertView,ViewGroup parent) {if (position >= 0 && position < lista.size()) {LayoutInflater inflater = actividad.getLayoutInflater();View view = inflater.inflate(R.layout.menu_item, null,true);TextView textView = (TextView) (view.findViewById(R.id.texto_item));String texto = lista.elementAt(position);textView.setText(texto);ImageView imageView = (ImageView) view.findViewById(R.id.icono);Context context = view.getContext();if (texto.contains(context.getString(R.string.menu_juego))) {imageView.setImageResource(android.R.drawable.ic_media_play);} else if (texto.contains(context.getString(R.string.menu_ayuda))) {imageView.setImageResource(android.R.drawable.ic_menu_help);} else if (texto.contains(context.getString(R.string.menu_ajustes))) {imageView.setImageResource(android.R.drawable.ic_menu_preferences);} else {imageView.setImageResource(android.R.drawable.ic_media_next );}return view;}return null;}public int getCount() {return lista.size();}public Object getItem(int arg0) {return lista.elementAt(arg0);}public long getItemId(int position) {return position;}}
Vector<String> items = new Vector<String>();items.add(getString(R.string.menu_juego));items.add(getString(R.string.menu_ajustes));items.add(getString(R.string.menu_ayuda));items.add(getString(R.string.menu_estadisticas));MiAdaptador adapt = new MiAdaptador(this, items);
setListAdapter(adapt);
The result is:
On click
To respond to click actions for an specific item you have to overwrite onListItemClick(ListView l, View v, int posicion, long id)
protected void onListItemClick(ListView l, View v, int posicion, long id) {String item = (String) getListAdapter().getItem(posicion);super.onListItemClick(l, v, posicion, id);}





Discussion