Create ListView in code
Description
The following code shows how to create a ListView.
Example
/*from www . j av a 2s .c om*/
package com.java2s.myapplication3.app;
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 MainActivity extends ListActivity {
String[] presidents = {
"XML",
"HTML",
"CSS",
"Java",
"Javascript"
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, presidents));
}
public void onListItemClick(
ListView parent, View v, int position, long id)
{
Toast.makeText (this,
"You have selected " + presidents [position],
Toast.LENGTH_SHORT).show();
}
}
Note
MainActivity class extends the ListActivity class. The ListActivity class extends the Activity class and it displays a list of items by binding to a data source.
There is no need to modify the main.xml file to include the ListView; the ListActivity class itself contains a ListView.