Simple listview example

1. Start with a simple layout for each line.

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp"
    android:textSize="20sp" >
</TextView>

Create activity extending ListActivity.

public class WordListActivity extends ListActivity {
	static final String[] words = new String[] { "Apple", "Bread",
		"Cat", "Dog", "Mat"};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setListAdapter(new ArrayAdapter(this, R.layout.list_word, words));

		ListView listView = getListView();
		listView.setTextFilterEnabled(true);
	}
}

2. If you want an action when a list item is touched, add a listener into the onCreate.

listView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
			    Toast.makeText(getApplicationContext(),
				((TextView) view).getText(), Toast.LENGTH_SHORT).show();
			}
		});

 

This entry was posted in Android. Bookmark the permalink.

Leave a Reply

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