Monday, October 19, 2009

ListView with more items on each entry, using SimpleAdapter

In the previous articles of ListView, ArrayAdapter are used. Only one item can be display on each entry.

In this article, SimpleAdapter is used. Such that we have more than one items on each entry.



It's a ListActivity list the ASCII symbols from 32 to 126, in which there are two items, the code and the symbol, will be display on each entry.

The ASCII symbols are converted using EncodingUtils.getAsciiString().

We have a List to hold the code:symbol pair for each entry, and use SimpleAdapter to adapte to the ListView.

All we need is two files only
/res/row.xml, which is the layout of each entry on the ListView
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text = " " />
<TextView android:id="@+id/code"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text = " : " />
<TextView android:id="@+id/symbol"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>


AndroidAscii.java
package com.exercise.AndroidAscii;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.util.EncodingUtils;

import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class AndroidAscii extends ListActivity
{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);

List<Map<String, CharSequence>> asciiPair =
new ArrayList<Map<String, CharSequence>>();

Map<String, CharSequence> asciidata;

for ( int i = 32; i <= 126; i++ )
{
asciidata = new HashMap<String, CharSequence>();

String strCode = String.valueOf(i);

byte[] data = {(byte) i};
CharSequence strSymbol = EncodingUtils.getAsciiString(data);

asciidata.put("Code", strCode );
asciidata.put("Symbol", strSymbol );
asciiPair.add(asciidata);
}

SimpleAdapter AsciiAdapter = new SimpleAdapter(
this,
asciiPair,
R.layout.row,
new String[] { "Code", "Symbol" },
new int[] { R.id.code, R.id.symbol } );

setListAdapter(AsciiAdapter);
}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);

String myAscii = l.getItemAtPosition(position).toString();
Toast.makeText(this, myAscii, Toast.LENGTH_LONG).show();
}
}


Download the files.

No comments: