views:

1005

answers:

3

I'm new to Android, and I really need to do it this way (I've considered doing it in another Activity), but can anyone show me a simple code (just the onCreate method) that can do Listview without ListActivity?

THanks

+3  A: 

If you have an xml layout for the activity including a listView like this

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent" 
android:layout_height="fill_parent">

<ListView android:id="@android:id/list"
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"
    android:layout_weight="fill_parent"

Then in your onCreate you could have something like this

setContentView(R.layout.the_view);
    ListView lv = (ListView)findViewById(R.id.list);
    lv.setAdapter(...
sadboy
A: 

You could also reference your layout, instantiate a layout object from your code, and then build the ListView in Java. This gives you some flexability in terms of setting dynamic height and width at runtime.

mobilekid
A: 

The following creates a simple ListView programmatically:

public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         String[] myList = new String[] {"Hello","World","Foo","Bar"};              
         ListView lv = new ListView(this);
         lv.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,myList));
         setContentView(lv);
}
ccheneson
Hi Cchenesson...when I follow this code, I get a "Edit Source" in my Eclipse (which means it doesn't work.) Why is that?
TIMEX
Weird - I created a new android prject, copy/paste the above, run it without any problems. Can you post the whole code for the activity? Where do you see that "Edit Source" in Eclipse?
ccheneson
Is it this problem you have? http://android.opensourceror.org/2010/01/18/android-source/
ccheneson