ListView: A view that shows items in a vertically scrolling list. The items
come from the {@link ListAdapter} associated with this view.
也就是说ListView的view和数据本身是分离的,它所需要的数据由ListAdapter提供,调用setAdapter方法给ListView添加ListAdapter。
ListAdapter:Extended {@link Adapter} that is the bridge between a {@link ListView}
and the data that backs the list.
ListView的使用主要是两点:
1.给ListView填充数据
2.实现对每一项的点击事件
1.给ListView填充数据
ListView的数据依赖于Adapter。常用的Adapter有ArrayAdapter,SimpleCursorAdapter,SimpleAdapter等
2.实现单项的点击事件
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View view,
int position, long id) {
// TODO Auto-generated method stub
}
});
示例:
package com.example.testlistview;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity {
ListView listView;
ArrayAdapter adapter;
ArrayList list;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView)findViewById(R.id.list_view);
list = new ArrayList();
list.add("Chinese");
list.add("English");
list.add("Math");
list.add("Physics");
list.add("Politics");
list.add("PE");
adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, list);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, "你点击的是"+list.get(position), Toast.LENGTH_SHORT).show();
}
});
}
}
阅读(1355) | 评论(0) | 转发(0) |