android中listview是一个很常用的控件,他用列表的形式来展现内容。
我们使用Android studio 创建一个项目,在activity_main.xml中书写:
| 
					 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19  | 
						<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:tools="http://schemas.android.com/tools"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:paddingBottom="@dimen/activity_vertical_margin"     android:paddingLeft="@dimen/activity_horizontal_margin"     android:paddingRight="@dimen/activity_horizontal_margin"     android:paddingTop="@dimen/activity_vertical_margin"     tools:context="com.example.napoleon.myapplication.MainActivity">     <ListView         android:layout_width="fill_parent"         android:layout_height="wrap_content"         android:id="@+id/listView"         android:layout_alignParentLeft="true"         android:layout_alignParentStart="true" /> </RelativeLayout>  | 
					
上面的代码我添加了一个listview.
下面我们需要给listview一个数据集合,让listview显示这些数据,我们如何绑定这些数据呢?那么就需要适配器和listview进行配合了。
| 
					 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29  | 
						import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.ArrayAdapter; import android.widget.ListView; public class MainActivity extends AppCompatActivity {     private ListView lv;     //定义arrayadapte     private ArrayAdapter<String> adapter;     @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);         adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1);         lv = (ListView) findViewById(R.id.listView);         //设置数据适配器         lv.setAdapter(adapter);         adapter.add("hello");         adapter.add("eoe");     } }  | 
					
上面定义了两个私有变量,listview和ArrayAdapter,分别代表一个listview控件和字符串泛型的数组适配器。在onCreate中绑定相应对象。
| 
					 1  | 
						adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1);  | 
					
这段话绑定了,android系统资源的列表项
| 
					 1  | 
						lv.setAdapter(adapter);  | 
					
此句是让listview设置数据适配器
| 
					 1  | 
						adapter.add("hello");  | 
					
这句就很好理解了,就是向适配器添加数据。
ok了,运行,我们的程序看看结果:
