Domanda

Is it possible to create a ListView and an adapter, add items to it programmatically without XML? If so, how?

È stato utile?

Soluzione

First, you need to initialize the ListView, then add it to the layout of your activity. You can read about doing this here: How to create a RelativeLayout programmatically with two buttons one on top of the other?

You would create a Layout, then create a ListView and add it to that layout.

Next, you need to create a custom adapter. You can read more about that here: http://developer.android.com/reference/android/widget/ListAdapter.html

For example, you could use an ArrayAdapter. http://developer.android.com/reference/android/widget/ArrayAdapter.html

An ArrayAdapter has a method

public View getView (int pos, View convertView, ViewGroup parent)

This method returns a view to display at position pos in the list. In this method, you would first see if you already have a view for this position (by checking convertView). If you don't, you would generate a new View however you want. You could do this in code, or better yet, you could use an XML file and inflate a view.

After you get your adapter setup, you call setAdapter on your ListView.

So for example, it might look something like this:

@Override
public void onCreate(Bundle savedInstanceState){
    LinearLayout ll = new LinearLayout(this);
    ListView lv = new ListView(this);
    YourAdapter adapter = new YourAdapter(<parameters here>);
    lv.setAdapter(adapter);

    ll.addView(lv, LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
    setContentView(ll);
}

Altri suggerimenti

Assuming you have knowledge about Fragments and ArrayAdapters, the simplest way is to extend ListFragment and add your adapter using setListAdapter(ArrayAdaper/some custom adapter object) convenience method. If you are not using the convenience method, you should use ListFragment.setListAdapter(...) Not ListView.setListAdapter(...).

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top