3

I'm having some trouble figuring something out that should be quite easy and straight forward. I have an activity that has a few Views in it including a ListView that currently is not populated.

How do you programmatically get a reference to that ListView and then set the items, each item being a TextView with the content then being XML String-Array items?

Getting reference I suppose is like this:

ListView incomeList = (ListView) findViewById(R.id.incomeList);

Also I have a this code in my strings.xml(Want to populate list with this array):

<string-array name="testArray">
   <item>Item1</item>
   <item>Item2</item>
   <item>Item3</item>
   <item>Item4</item>
   <item>Item5</item>
</string-array>

And then lastly I have this other layout xml file that I should have according to all the tuts out there. list_item.xml

<?xml version="1.0" ebcoding="utf-8">
<TextView xmlns:android="blablabla..."
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:padding="10dp"
   android:textSize="16sp"
</TextView>

All of the tutorials I followed on the web though is helpful if a ListView is the only View in your activity. Whereas in my case I have quite a few Views including buttons, textviews etc etc.(If this might be helpful to know). Also do I extend my class with ListActivity or since I have other views in there, just extend normally with Activity?

1 Answer 1

3
+50

You don't need to extend ListActivity. Just extend a regular activity.

Steps:

A) get your ListView. You're doing it right in your question.

B) create an ArrayAdapter. You must pass a Context (if you do it on the Activity, pass that Activity), an int representing a Layout which ONLY contains a TextView (Like the one in your question), and a String[] containing all the items you need.

Should look like this:

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item, getResources().getStringArray(R.array.testArray);

C) lv.setAdapter(adapter);

Pretty straightforward.

Sign up to request clarification or add additional context in comments.

1 Comment

It's working! Thank you very much, you're the proud owner of 50rep.. :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.