Populating Android ListView from Java

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
 
 
    <ListView
      	android:id="@+id/statesList"
      	android:layout_width="match_parent"
      	android:layout_height="fill_parent" />
 
</LinearLayout>
package com.w3mentor.android;
 
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
 
public class MyListViewActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
 
        ListView statesList = (ListView)findViewById(R.id.statesList);
 
        final String[] nationalstates = new String[] {		"California",
        									"Nevada",
        									"NewYork",
        									"NorthCarolina",
        									"Washington",
        									"Kansas",
        									"DC"
        								};
 
      ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, nationalstates);
 
      bandList.setAdapter(adapter);
 
      bandList.setOnItemClickListener(new OnItemClickListener() {
 
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			Toast.makeText(getApplicationContext(), nationalstates[position], Toast.LENGTH_SHORT).show();
 
		}
	});
 
    }
 
    }

Enjoyed this post? Share it!

 

Leave a comment

Your email address will not be published.