Android基础(六) ListView - ArrayAdapter

一、概述

ListView和SpinnerView一样适合用来存放拥有多个元素的数据集。下面Demo里面,先定义了一个String数组,然后用它来构建一个ArrayAdapter。再将ListView实例与ArrayAdapter关联。

二、实例

【效果图】
 

【代码节选】
package enleo.ListViewExample; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; public class ListViewExample extends Activity { String[] presidents = { "Dwight D. Eisenhower", "John F. Kennedy", "Lyndon B. Johnson", "Richard Nixon", "Gerald Ford", "Jimmy Carter", "Ronald Reagan", "George H. W. Bush", "Bill Clinton", "George W. Bush", "Barack Obama" }; private ListView mLv; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.listview); mLv = (ListView)findViewById(R.id.listView1); mLv.setAdapter((new ArrayAdapter(this, android.R.layout.simple_list_item_1, presidents))); mLv.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, int position, long id) { // TODO Auto-generated method stub Toast.makeText(getBaseContext(), "You have clicked "+presidents[position]+" position="+position+" id="+id, Toast.LENGTH_SHORT).show(); } }); } }  

 

三、注意

1.继承关系

2.public void onItemClick(AdapterView parent, View view, int position, long id) 

postion参数 和 id参数, 这两个参数的异同以后再分析。

你可能感兴趣的:(Android基础(六) ListView - ArrayAdapter)