ListView 是以列表的形式呈现多个item,通过item呈现每一个数据。
.ListView & ArrayAdapter 应用的基本实现:
获得ListView(首先在布局文件中定义listview)
构建Adapter(选择ArrayAdapter)
关联Adapter(调用listview的setAdapter方法)
布局文件中需要添加一个ListView:
<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"
tools:context=".MainActivity" >
<ListView
android:id="@+id/listId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
</RelativeLayout>
MainActivity里面的内容为:
package com.example.listview;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//1.获得ListView
ListView lsv=(ListView) findViewById(R.id.listId);
//2.构建Adatper(注意Adapter的类型和构造方法)
ArrayAdapter<String> adapter=
new ArrayAdapter<String>(
this, //context 资源访问对象(将此对象传给adapter,是adapter中要借助此对象获得系统中的一个资源)
android.R.layout.simple_list_item_1
);
adapter.add("Music-01");
adapter.add("Music-01");
adapter.addAll("Music-03","Music-04");
//3.关联适配器
lsv.setAdapter(adapter);
}
}