I want to show these itens at my ListView
<string-array name="bookmark_titles">
<item>Google</item>
<item>Bing</item>
<item>Gmail</item>
</string-array>
I have a method that gets these values.
public static Collection getBookmarks(Context context) {
Collection bookmarks = new Collection();
String[] titles = context.getResources().getStringArray(R.array.bookmark_titles);
for (int i = 0; i < titles.length; i ++) {
bookmarks.add(titles[i]);
}
return bookmarks;
}
How can I call the method getBookmarks in my main.java to fill the ListView?
I have already created a ListView. It is:
<ListView
android:id="@+id/my_listView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:divider="#ECECEC"
android:dividerHeight="1sp" />
main.java I am trying to do something like this:
ListView lv = (ListView) findViewById(R.id.my_listView);
ArrayList<Bookmark> my_array = BookmarkCollection.getTestBookmarks(context);
adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, my_array);
lv.setAdapter(adapter);
You can create your adapter with a one liner, check out the static method ArrayAdapter createFromResource(Context context, int textArrayResId, int textViewResId)
The first argument will probably be your Activity, the second is R.array.bookmark_titles
, and the third is a layout to use.
To clarify based on the comments, the method accepts int
, which is exactly what the constants in your generated R
class are stored as.
Here's a complete example, assuming this is being called from an Activity:
ArrayAdapter<CharSequence> aa = ArrayAdapter.createFromResource(this, R.array.bookmark_titles, android.R.layout.simple_list_item_1);
myListView.setAdapter(aa);
In this case, android.R.layout.simple_list_item_1
refers to an XML layout that is provided by the Android SDK. You can change this if needed.
You can do this with an ArrayAdapter and have it use either an Array or a List to give it data
lv.setAdatper(new ArrayAdapter<String>(context, R.layout.some_layout_to_use, R.id.some_textview_in_layout, listData);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With