Is it possible to create a ListView and an adapter, add items to it programmatically without XML? If so, how?
-
2Yes, there is a way to do it.Cruceo– Cruceo2014-03-20 19:11:05 +00:00Commented Mar 20, 2014 at 19:11
-
@Guardanis You know how I can do ?Fcps– Fcps2014-03-20 19:23:01 +00:00Commented Mar 20, 2014 at 19:23
-
ListView myListView = new ListView(context); Aside from that, this site is to help you fix problems, not program an entire thing for you. If you have a specific question or problem, show us what you've done and we can help you fix it. We can't just magically predict what you've done or build the whole thing for you. But here's a .0005 second Google search for you: stackoverflow.com/a/12795518/1426565Cruceo– Cruceo2014-03-20 19:51:28 +00:00Commented Mar 20, 2014 at 19:51
2 Answers
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);
}
5 Comments
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(...).