ListView+ArrayAdapterについてのメモ

Activity

public class SandboxActivity extends Activity {
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		ListAdapter adapter =
			new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, new String[] { "hoge", "fuga" });
		
		ListView listView = (ListView) findViewById(R.id.ListView01);
		listView.setAdapter(adapter);
	}
}

ListViewにArrayAdapterをセット。ArrayAdapterにより1アイテムのレイアウトと対応するオブジェクト(の配列かリスト)を設定できる。上記はコンストラクタで配列を設定。あとから要素をadd()することも出来る。

レイアウトの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/ListView01" android:layout_width="match_parent"
		android:layout_height="wrap_content"></ListView>
</LinearLayout>

LinearLayoutのなかにListViewを配置している。ScrollViewを使わなくても、画面内に収まらないListViewは勝手にスクロールしてくれる。むしろScrollViewのなかにListViewを使うと、ちゃんと表示されないバグ?があるようだ。(Issue 6552 - android - ListView in ScrollView display only first 2 items by default, other after scroll. - Project Hosting on Google Code

textViewResourceId

コンストラクタに指定しているandroid.R.layout.simple_list_item_1、これはlayoutのxmlで、ソースは/base/core/res/res/layout/simple_list_item_1.xmlで見れます。

<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2006 The Android Open Source Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at
  
          http://www.apache.org/licenses/LICENSE-2.0
  
     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:gravity="center_vertical"
    android:paddingLeft="6dip"
    android:minHeight="?android:attr/listPreferredItemHeight"
/>

ViewGroupもなくTextViewがひとつ入っているのみです。
ArrayAdapterのコンストラクタにresourceを渡さないと、Adapter内部のView、つまりgetViewの結果は指定したTextViewになります。そこに、ArrayAdapterにおけるTのtoString()された結果をsetTextします。
resourceを渡した場合、渡したviewがgetViewの結果になります。textViewはそこからfindViewByIdされます。

あわせてよみたい

List View | Android Developers List Viewのチュートリアル