You may create a class with two fields: one for text and another for ID. And implement toString
method as returning the value of the text field. Here is an example:
package org.me.adaptertest;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends ListActivity {
public static class Element {
private String mText;
private long mId;
public Element(String text, long id) {
mText = text;
mId = id;
}
public long getId() {
return mId;
}
public void setId(long id) {
mId = id;
}
public String getmText() {
return mText;
}
public void setmText(String mText) {
this.mText = mText;
}
@Override
public String toString() {
return mText;
}
}
private List<Element> mItems;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
mItems = new ArrayList<MainActivity.Element>();
mItems.add(new Element("Element 1", 1));
mItems.add(new Element("Element 2", 2));
mItems.add(new Element("Element 3", 3));
setListAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1,
android.R.id.text1, mItems));
getListView().setOnItemClickListener(new ListView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MainActivity.this,
"ID is " + mItems.get(position).getId(),
Toast.LENGTH_SHORT).show();
}
});
}
}