ListView

来源:互联网 发布:在家数据录入员 编辑:程序博客网 时间:2024/05/16 18:08

ListView一般的两种基本功能

  1.将数据填充到布局。

  2.处理用户的选择点击等操作。

第一点很好理解,ListView就是实现这个功能的。第二点也不难做到,在后面的学习中读者会发现,这非常简单。

一个ListView的创建需要3个元素。

1ListView中的每一列的View

2)填入View的数据或者图片等。

3)连接数据与ListView的适配器。

也就是说,要使用ListView,首先要了解什么是适配器。适配器是一个连接数据和AdapterViewListView就是一个典型的AdapterView,后面还会学习其他的)的桥梁,通过它能有效地实现数据与AdapterView的分离设置,使AdapterView与数据的绑定更加简便,修改更加方便

Android中提供了很多的Adapter,表4-5列出了常用的几个。

4-5 常用适配器

Adapter


ArrayAdapter<T>


SimpleAdapter


SimpleCursorAdapter


BaseAdapter


 

 其实适配器还有很多,要注意的是,各种Adapter只不过是转换的方式和能力不一样而已。下面就通过使用不同的Adapter来为ListView绑定数据(SimpleCursorAdapter暂且不讲,后面讲SQLite时会介绍)。

4.12.1 ListView使用ArrayAdapter

ArrayAdapter可以实现简单的ListView的数据绑定。默认情况下,ArrayAdapter绑定每个对象的toString值到layout中预先定义的TextView控件上。ArrayAdapter的使用非常简单。

实例:

工程目录:EX_04_12

在布局文件中加入一个ListView控件。

<?xml version="1.0" encoding="utf-8"?><LinearLayout    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:orientation="horizontal"    tools:context="com.example.scxh.para.ParaMainActivity">    <
ListView
android:id="@+id/t1" android:layout_width="150dp" android:layout_height="150dp" android:src="@drawable/a11"/>
</LinearLayout>
复制代码

然后在Activity中初始化。

复制代码
package com.ittx.android1601.adapter;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.widget.ArrayAdapter;import android.widget.ListView;import com.ittx.android1601.R;public class MyArrayAdpaterActivity extends AppCompatActivity {    public ListView mListView;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_my_array_adpater_layout);        // TODO: 2016/6/1 实例化控件ListView         mListView = (ListView) findViewById(R.id.adapter_array_listview);        // TODO: 2016/6/1 构造数据源  arrays         String[] arrays = new String[]{"android","ios","java","j2ee","wphone","net","javascript","spring","structs","html","css","hibernate"};        // TODO: 2016/6/1 实例适配器  adapter         ArrayAdapter adapter = new ArrayAdapter(this,R.layout.item_adapter_array_view,arrays);//        ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,arrays);        // TODO: 2016/6/1 设置adapter        mListView.setAdapter(adapter);    }}
0 0
原创粉丝点击