适配器AdapterView(ArrayAdapter SimpleAdapter BaseAdapter)

Android中对于适配器的理解:

android开发中会大量使用到Listview  而 ListView 需要适配器才能使用,不同场合使用不同的适配器。接了下来 浅谈一下三个常用的适配器,概念及其使用方法。


ArrayAdapter(数组适配器) 一般用于显示一行的文本信息,所以比较简单。但是每个列表项只能是TextVIew 

ArrayAdapter<String> adapter=new ArrayAdapter<String>(context, resource, textViewResourceId);

上面这行代码用来装配数据,要装配这些数据就需要一个连接ListView视图对象和数组数据的适配器来两者的配合工作

context:用来连接上下文,类与类之间的相关联

resources:布局文件ID,用来数据的显示

textViewResourceId:数据源,用来为列表提供数据 


xml文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="ArrayAdapter 数组适配器例子" />
    <ListView 
        android:id="@+id/listview"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        />

</LinearLayout>


Activity:

import java.util.ArrayList;

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

public class Demo13Activity extends Activity {
    private ListView lv;
    private ArrayList<String> list = new ArrayList<String>();    //声明一个List数组用于存放数据
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        lv = (ListView)findViewById(R.id.listview);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(       //ArraryAdapter数组适配器
                this,
                android.R.layout.simple_expandable_list_item_1,
                getData());<span style="white-space:pre">					</span>      //添加数据
        lv.setAdapter(adapter);
    }
    
    private ArrayList<String> getData()
    {
        list.add("ListView 第一行");
        list.add("<span style="font-family: Arial, Helvetica, sans-serif;">ListView 第二行</span><span style="font-family: Arial, Helvetica, sans-serif;">");</span>
        list.add("<span style="font-family: Arial, Helvetica, sans-serif;">ListView 第三行</span><span style="font-family: Arial, Helvetica, sans-serif;">");</span>
        return list;
    }
}


SimpleAdapter:扩展性较强的适配器,可以适配我们各种想要的布局,而且方式较为简单。

SimpleAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to)

上面这段代码也是用来装配数据的。

context:联系上下文,用来关联simpleAdapter运行的上下文。

data:用来存储数据,比如在getData()中存放的数据,类型要与定义一致,每条项目要与from所指条目一致。

resources:布局文件ID

from:添加到map上相关联,数组里是列名称的含义,通过名称添加数据  (通过to找到空间ID,赋予ID一个from中的名称)

to:数组里的ID是各个空间的ID,需要与from上的名称相对应

如:   map.put("img", R.drawable.e001);   "img"对应着空间中的某个ID,添加drawable文件在该空间中显示
<span style="font-family: Arial, Helvetica, sans-serif;">        map.put("title", "小宗");</span>
        map.put("info", "电台DJ");


例子一:

xml文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal" >

    <ImageView 
        android:id="@+id/img"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="3px"
        />
    <LinearLayout 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        >
        <TextView 
            android:id="@+id/title"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:textSize="16sp"
            />
        <TextView
            android:id="@+id/info"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:textSize="10sp"
            />
    </LinearLayout>

</LinearLayout>


Activity文件:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.ListActivity;
import android.os.Bundle;
import android.widget.SimpleAdapter;

public class Demo13Activity extends ListActivity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SimpleAdapter adapter = new SimpleAdapter(this, getData(),      //simpleAdapter中对应的五个参数
                R.layout.main, new String[] { "img", "title", "info" }, //(上下文,数据源,布局文件,)
                new int[] { R.id.img, R.id.title, R.id.info });
        setListAdapter(adapter);
    }

    private List<Map<String, Object>> getData() {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("img", R.drawable.e001);
        map.put("title", "小宗");
        map.put("info", "电台DJ");
        list.add(map);

        map = new HashMap<String, Object>();
        map.put("img", R.drawable.e002);
        map.put("title", "貂蝉");
        map.put("info", "四大美女");
        list.add(map);

        map = new HashMap<String, Object>();
        map.put("img", R.drawable.e04b);
        map.put("title", "奶茶");
        map.put("info", "清纯妹妹");
        list.add(map);

        map = new HashMap<String, Object>();
        map.put("img", R.drawable.e04e);
        map.put("title", "大黄");
        map.put("info", "是小狗");
        list.add(map);

        map = new HashMap<String, Object>();
        map.put("img", R.drawable.e11a);
        map.put("title", "hello");
        map.put("info", "every thing");
        list.add(map);

        map = new HashMap<String, Object>();
        map.put("img", R.drawable.e11d);
        map.put("title", "world");
        map.put("info", "hello world");
        list.add(map);

        return list;
    }
}


例子二:自定义布局,显示网络资源,ViewBinder的使用
由于显示了网络资源,所以要记得在文件清单中添加权限

<pre name="code" class="java"><uses-permission android:name="android.permission.INTERNET"/>

 xml文件: 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

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

</LinearLayout>


Activity:

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.SimpleAdapter.ViewBinder;

public class Demo13Activity extends Activity {
    private ListView lv;
    private static final String iphoneUrl = "http://www.51aigoo.com/images/20100107/6b21df8c2419480e.jpg";
    private static final String macbookproUrl = "http://www.esundigi.net/images/goods/20110317/6ece8f319694f0b1.jpg";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mylist);
        lv = (ListView)findViewById(R.id.listview);
    
        SimpleAdapter adapter = new SimpleAdapter(
                this, 
                getData(),
                R.layout.main,
                new String[] {"img","title","info"},
                new int[] { R.id.img, R.id.title, R.id.info});
        //setListAdapter(adapter);
        adapter.setViewBinder(new MyViewBinder());
        lv.setAdapter(adapter);
        

    }
    //获取网络图片资源,返回类型是Bitmap,用于设置在ListView中
    public Bitmap getBitmap(String httpUrl)
    {
        Bitmap bmp = null;
        //ListView中获取网络图片
        try {
            URL url = new URL(httpUrl);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            InputStream is = conn.getInputStream();
            bmp = BitmapFactory.decodeStream(is);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return bmp;
    }
    //ListView上需要显示的数据
    private List<Map<String, Object>> getData() {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        Map<String, Object> map = new HashMap<String, Object>();
        //设置绑定是数据是图片
        map.put("img", getBitmap(iphoneUrl));
        map.put("title", "iphone4");
        map.put("info", "可远观而买不起嫣");
        list.add(map);
        
        map = new HashMap<String, Object>();
        map.put("img", getBitmap(macbookproUrl));
        map.put("title", "Macbook pro");
        map.put("info", "明年买个玩玩");
        list.add(map);

        return list;
    }
}
//实现ViewBinder接口
class MyViewBinder implements ViewBinder
{
    /**
     * view:要板顶数据的视图
     * data:要绑定到视图的数据
     * textRepresentation:一个表示所支持数据的安全的字符串,结果是data.toString()或空字符串,但不能是Null
     * 返回值:如果数据绑定到视图返回真,否则返回假
     */
    @Override
    public boolean setViewValue(View view, Object data,
            String textRepresentation) {
        if((view instanceof ImageView)&(data instanceof Bitmap))
        {
            ImageView iv = (ImageView)view;
            Bitmap bmp = (Bitmap)data;
            iv.setImageBitmap(bmp);
            return true;
        }
        return false;
    }
    
    
}












评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值