Android How-To: Create Spinners, ListViews and Context Menues programmatically

| | Comments (0)
[NOTE] Updated on 2009-01-17: Adopted Samples to final release of Android SDK (1.0 R2)

An Android user interface is created by specifying a layout XML usually, but sometimes you need to create your interfaces or parts of it "on-the-fly" in your programm code. This is not very easy sometimes because of the lack of documentation. The following code snippets show you how I could create a Spinner and a ListView widget programmatically:

...
public class Sample extends Activity
  ...
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    ...
    
//Creating a spinner
Spinner spinner = new Spinner(this); ArrayAdapter spinnerArrayAdapter = new ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_item, new String[] { "Apple", "Peach", "Banana" }); spinner.setAdapter(spinnerArrayAdapter);
//Add spinner to this activity's view (a LinearLayout)
mainLayout.addView(spinner, new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)); ... } }
...
public class Sample extends Activity
  ...
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    ...
    
//Creating a ListView with Context Menu
ListView listView = new ListView(this); ArrayAdapter listViewArrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, new String[] { "Apple", "Peach","Banane" }); listView.setAdapter(listViewArrayAdapter); listView.setFocusableInTouchMode(true); listView.setOnFocusChangeListener( new View.OnFocusChangeListener() { @Override public void onFocusChange(View arg0, boolean arg1) { Log.i("SampleApp", "onFocusChanged() - view=" + arg0); } }); listView.setOnItemClickListener( new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView adapterView, View view, int arg2, long arg3) { int selectedPosition = adapterView.getSelectedItemPosition(); Log.i("SampleApp", "Click on position"+selectedPosition); } }); listView .setOnCreateContextMenuListener( new View.OnCreateContextMenuListener() { public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) { AdapterContextMenuInfo mi = (AdapterContextMenuInfo) menuInfo; menu.add(0, 0, 0, "Context-Menu-Entry"); } }); ... } }

Leave a comment

About this Entry

This page contains a single entry by Harald Lacherstorfer published on March 18, 2008 11:04 PM.

Android How-To: Invoke a phone call Activity was the previous entry in this blog.

Exploring jQuery is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.