This article explains the ListView with ListActivity in Android. Android Studio is used to create the sample.
Simply put, what we do when we create a ListView using XML is first we extend the Activity class that provides setContentView() in which we the layout id like this (R.layout.layoutid). So when we run the application it displays the list view on the screen. To show a list view on the screen without using an XML file we need to extend the ListActivity class in our class. To get the list view we call getListView() provided by the ListActivity class. Now do all the things you do when you create the list view using an XML file.
Step 1
Create the project like this:
Step 2
Create a Java file and write this:
- package com.listactivtyapplication;
- import android.os.Bundle;
- import android.app.Activity;
- import android.view.Menu;
- import android.app.ListActivity;
- 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 MainActivity extends ListActivity
- {
- ListView listview;
- String[] countries = new String[]
- {
- "Samsung",
- "Nokia",
- "Blackberyy",
- "LG",
- "Motorolla",
- "Apple",
- "Karbon",
- "Micromax",
- "Zen",
- };
- @Override
- public void onCreate(Bundle savedInstanceState)
- {
- super.onCreate(savedInstanceState);
- listview = getListView();
- ArrayAdapter < String > listadapter = new ArrayAdapter < String > (this, android.R.layout.simple_list_item_1, countries);
- listview.setAdapter(listadapter);
- listview.setOnItemClickListener(new OnItemClickListener()
- {
- @Override
- public void onItemClick(AdapterView < ? > adapterView, View view, int i, long l)
- {
- Toast.makeText(getBaseContext(), "You selected : " + countries[i], Toast.LENGTH_SHORT).show();
- }
- });
- }
- }
Step 3
Android menifect.xml file
- <?xml version="1.0" encoding="utf-8"?>
- <manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.listactivtyapplication"
- android:versionCode="1"
- android:versionName="1.0" >
-
- <uses-sdk
- android:minSdkVersion="7"
- android:targetSdkVersion="16" />
-
- <application
- android:allowBackup="true"
- android:icon="@drawable/ic_launcher"
- android:label="@string/app_name"
- android:theme="@style/AppTheme" >
- <activity
- android:name="com.listactivtyapplication.MainActivity"
- 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>
Step 4