Aug 26, 2011

Load ListView contents from XML resources

In the last posts A simple ListView using android.R.layout.simple_list_item_1 layout and ListView with your own layout; contents of ListView is defined in Java code. It can be defined in XML resources, and fill in ArrayAdapter by calling ArrayAdapter.createFromResource() method.

Create /res/values/month.xml file
<?xml version="1.0" encoding="utf-8"?>

<resources>
<string-array name="month">
<item>January</item>
<item>February</item>
<item>March</item>
<item>April</item>
<item>May</item>
<item>June</item>
<item>July</item>
<item>August</item>
<item>September</item>
<item>October</item>
<item>November</item>
<item>December</item>
</string-array>
</resources>


Modify onCreate() to create ArrayAdapter from resource.
    @Override

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myList = (ListView)findViewById(R.id.list);

ArrayAdapter<CharSequence> adapter
= ArrayAdapter.createFromResource(this,
R.array.month,
R.layout.mylistlayout);

myList.setAdapter(adapter);

}





Related:

- ListView with multiple choice






1 comment:

  1. thank you for your help!

    but I was struggled to find what is 'mylistlayout'

    Now I know it's the XML file 'mylistlayout.xml' from your former subject 'ListView with your own layout' !!

    Please, please, please! Be more explicit next time..!

    ReplyDelete

Infolinks In Text Ads