Tuesday, August 14, 2012

Load ListView contents from XML resources in Android

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);

   }

No comments:

Post a Comment