ListActivity.java
package com.jamesfroggatt.listviewadapterexample1.app; import android.app.Activity; import android.os.Bundle; import android.widget.ArrayAdapter; import android.widget.ListView; public class ListActivity extends Activity { // Initialize the array String[] numbersArray = { "One", "Two", "Three", "Four", "Five"}; // Declare the UI components private ListView numbersListView; private ArrayAdapter arrayAdapter; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // wet which layout xml to use as this layout (activity_list.xml) setContentView(R.layout.activity_list); // Initialize the UI components numbersListView = (ListView) findViewById(R.id.numbers_list); // For this moment, you have ListView where you can display a list. // But how can we put this data set to the list? // // This is where you need an Adapter // context - The current context. // resource - The resource ID for a layout file containing a layout // to use when instantiating views. // From the third parameter, you plugged the data set to adapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, numbersArray); // By using setAdapter method, you plugged the ListView with adapter numbersListView.setAdapter(arrayAdapter); } }
layout/Activity_List.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".ListActivity" > <ListView android:id="@+id/numbers_list" android:layout_width="match_parent" android:layout_height="wrap_content" > </ListView> </LinearLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.jamesfroggatt.listviewadapterexample1.app" > <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <activity android:name="com.jamesfroggatt.listviewadapterexample1.app.ListActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>