您的位置:首页 > 移动开发 > Android开发

Android ListView与Arrayadapter之间的搭配使用

2015-04-18 14:16 471 查看
在做安卓开发的时候很多时候都要用到ListView来显示数据,ListView使用的也很广泛,用到了ListView就会使用到adapter适配器,关键就在于adapter,刚开始学安卓的时候就根本不知道怎么根据自己的需要来选择对应的adapter,今天自己也就来总结一下,方便查看。

在ListView中使用最多的adapter是ArrayAdapter、SimpleAdapter、BaseAdapter。ArrayAdapter从名称上来看就知道是用来显示数组的,SimpleAdapter是用来显示比较复杂的数据,我一般用来显示图片+标题。BaseAdapter可以实现复杂的列表布局,由于BaseAdapter是一个抽象类,使用该类需要自己写一个适配器继承该类,正是由于继承了该类,需要我们重写一些方法,让我们可以在代码里控制列表的样式,更加灵活。

一、ArrayAdapter显示简单的数据

布局文件activity_main.xml

<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=".MainActivity" >

<ListView
android:id="@+id/listview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>

</RelativeLayout>
很简单的一个布局文件,只是一个ListView。

MainActivity.java

package com.example.listview01;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends Activity {
private ListView listview;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

listview = (ListView) findViewById(R.id.listview);
String [] list = new String []{"姓名:张三","性别:男","地址:重庆市沙坪坝区沙正街174号"};

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, list);
listview.setAdapter(adapter);
}
}


ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, list)

第一个参数就不说了,第二个参数是Android提供的一个布局文件,第三个参数是要显示的数据。

在Android为ListView指定的外观形式通常有一下几个。

simple_list_item_1:每个列表都是一个普通的文本。

simple_list_item_2:每个列表都是一个普通的文本(字体稍大)。

simple_list_item_checked:每个列表都有一个一选中的列表项。

simple_list_item_multiple_choice:每个列表都是带复选框的文本。

simple_list_item_multiple_choice:每个列表都是带复选框的文本。

测试结果如下:



但是这个看起来还是很单调,要是想要ListView每个item的自定义的话,系统提供的simple_list_item_1就不能满足要求了,在这里我们就要自己重新写一个布局文件了,由上面的描述(每个列表都是一个普通的文本)可知,我们也需要一个只有一个不同文本的布局文件,然后进行自定义。

item.xml

<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#00ff00"
android:textSize="30sp"
android:background="#000000"/>
这里注意:上面写的很明白了,是只包含一个文本的布局文件。作者在第一次使用自定义布局的时候是在一个LinearLayout中添加了一个TextView,导致一直报错

,后来研究了一下才知道是只能有一个文本布局。

在这个自定义的TextView中定义了一个黑色的背景,字体放大,设置了字体颜色,然后在程序的第20行代码改成

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,item, list);


下面看效果图:



有了自定义的item就可以根据自己的需求定义了~~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐