如果程序的窗口僅僅需要顯示一個列表,則可以直接讓Activity繼承ListActivity來實現,ListActivity的子類無須調用setContentView()方法來顯示某個界面,而是可以直接傳入一個內容Adapter,ListActivity的子類就呈現出一個列表。
xml代碼:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ListView android:id="@+id/android:list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#0000ff"
android:layout_weight="1"
android:drawSelectorOnTop="false"/>
</LinearLayout>
import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
public class MainActivity extends ListActivity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// 無需使用佈局文件
String[] arr = { "孫悟空", "豬八戒", "唐僧" };
// 創建ArrayAdapter對象
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice, arr);
// 設置該窗口顯示列表
setListAdapter(adapter);
}
}
顯示效果:
ListActivity實現列表學習筆記