学习目的:1.了解ListView(列表)的用法 2.定制listview的界面(自定义适配器) 3.提升ListView的运行效率
4.ListView的点击事件
ListView(列表)的用法
1 | ListView需要大量数据 来源数据库 或自定义 |
4.MianActivity类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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46public class MainActivity extends AppCompatActivity {
private List<Fruit> fruitList = new ArrayList<Fruit>();//用ArrayList()方法声明一个fruitList列表 指定泛型为Fruit
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initFruits(); // 初始化水果数据
FruitAdapter adapter = new FruitAdapter(MainActivity.this, R.layout.fruit_item, fruitList);//第一个参数 传入水果对象 布局ID 水果列表
ListView listView = (ListView) findViewById(R.id.list_view);//导入布局id
listView.setAdapter(adapter);//启动适配器
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {//给listview设置监听器
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Fruit fruit = fruitList.get(position);
Toast.makeText(MainActivity.this, fruit.getName(), Toast.LENGTH_SHORT).show();//设置逻辑
}
});
}
private void initFruits() {
for (int i = 0; i < 2; i++) {//循环两次是出于谨慎
Fruit apple = new Fruit("Apple", R.drawable.apple_pic);
fruitList.add(apple);
Fruit banana = new Fruit("Banana", R.drawable.banana_pic);
fruitList.add(banana);
Fruit orange = new Fruit("Orange", R.drawable.orange_pic);
fruitList.add(orange);
Fruit watermelon = new Fruit("Watermelon", R.drawable.watermelon_pic);
fruitList.add(watermelon);
Fruit pear = new Fruit("Pear", R.drawable.pear_pic);
fruitList.add(pear);
Fruit grape = new Fruit("Grape", R.drawable.grape_pic);
fruitList.add(grape);
Fruit pineapple = new Fruit("Pineapple", R.drawable.pineapple_pic);
fruitList.add(pineapple);
Fruit strawberry = new Fruit("Strawberry", R.drawable.strawberry_pic);
fruitList.add(strawberry);
Fruit cherry = new Fruit("Cherry", R.drawable.cherry_pic);
fruitList.add(cherry);
Fruit mango = new Fruit("Mango", R.drawable.mango_pic);
fruitList.add(mango);
}
}
3.ListView的优化
1 | 需要优化的点:1.getView每一次滑动都要将布局重载!(效率低) |
4.ListView的点击事件
1 | 简单,不赘述。 |