Java (Android): リストビュー

ListViewActivity

package jp.feb19.snippets;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class ListViewActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		// Android 標準のリストレイアウト (android.R.layout.simple_list_item_1) を使用
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
		for (int i = 0; i < 100; i++) {
			adapter.add(String.valueOf(i));
		}
		
		ListView listView = new ListView(this);
		setContentView(listView, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				ListView listView = (ListView)parent;
				String item = (String)listView.getItemAtPosition(position);
				Toast.makeText(ListViewActivity.this, item, Toast.LENGTH_LONG).show();
			}
		});
	}
}