Android中适配器的应用

本文详细介绍了Android中ListView的几种适配器使用方法,包括ArrayAdapter、SimpleAdapter及BaseAdapter的实现细节与实例代码,帮助开发者更好地理解和应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一,适配器.          顾名思义,就是把一些数据给弄得适当,适合以便于在View上显示。可以看作是
界面数据绑定的一种理解。它所操纵的数据一般都是一些比较复杂的数据,如数组,链表,数据库,集合等。适配器就像显示器,把复杂的东西按人可以接受的方式来展现。那么适配器是怎么处理得到的数据,并把它显示出来的呢。其实很简单,说白了适配器它也是一个类,在类里面它实现了父类的这几个方法:

publicint getCount() //得到数据的行数
public Object getItem(int position)//根据position得到某一行的记录
public long getItemId(int position)//得到某一条记录的ID
//下面这个方法是最重要的相比于其它几个方法,它显式的定义了,适配器将要以什么样的方式去显示我们所填充的数据,在自定义的适配器里面我们通常会给它写个布局文件
publicView getView(int position, View convertView, ViewGroup parent)  

我们常用的适配器一共有三个,当然不包含自定义的适配器,哪三个 那就是ArrayAdapter,SimpleAdapter,SimpleCursorAdapter 这三个,他们都是继承BaseAdapter
其中以ArrayAdapter最为简单,只能展示一行字。SimpleAdapter有最好的扩充性,可以自定义出各种效果。SimpleCursorAdapter可以认为是SimpleAdapter对数据库的简单结合,可以方面的把数据库的内容以列表的形式展示出来。

1)ArrayAdapter

列表的显示需要三个元素:

a.ListVeiw 用来展示列表的View。

b.适配器 用来把数据映射到ListView上的中介。

c.数据    具体的将被映射的字符串,图片,或者基本组件。

案例一

复制代码
public class ArrayAdapterActivity extends ListActivity {
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         //列表项的数据
         String[] strs = {"1","2","3","4","5"};
         ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_expandable_list_item_1,strs);
         setListAdapter(adapter);
     }
 }
复制代码

案例二

复制代码
    public class MyListView extends Activity {
    
        private ListView listView;
        //private List<String> data = new ArrayList<String>();
        @Override
        public void onCreate(Bundle savedInstanceState){
            super.onCreate(savedInstanceState);
             
            listView = new ListView(this);
            listView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1,getData()));
            setContentView(listView);
        }
         
        private List<String> getData(){
             
            List<String> data = new ArrayList<String>();
            data.add("测试数据1");
            data.add("测试数据2");
            data.add("测试数据3");
            data.add("测试数据4");
             
            return data;
        }
    }

2)SimpleAdapter
  simpleAdapter的扩展性最好,可以定义各种各样的布局出来,可以放上ImageView(图片),还可以放上Button(按钮),CheckBox(复选框)等等。下面的代码都直接继承了ListActivity,ListActivity和普通的Activity没有太大的差别,不同就是对显示ListView做了许多优化,方面显示而已。

案例一

simple.xml

复制代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ImageView
android:id="@+id/img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
/>
<TextView
android:id="@+id/title"
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
android:textColor="#ffffff"
android:textSize="20sp"
/>
</LinearLayout>
复制代码
复制代码
public class SimpleAdapterActivity extends ListActivity {
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         
         SimpleAdapter adapter = new SimpleAdapter(this, getData(), R.layout.simple, new String[] { "title",  "img" }, new int[] { R.id.title, R.id.img });
         setListAdapter(adapter);
     }
     
     private List<Map<String, Object>> getData() {
         //map.put(参数名字,参数值)
         List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
         Map<String, Object> map = new HashMap<String, Object>();
         map.put("title", "摩托罗拉");
         map.put("img", R.drawable.icon);
         list.add(map);
         
         map = new HashMap<String, Object>();
         map.put("title", "诺基亚");
         map.put("img", R.drawable.icon);
         list.add(map);
         
         map = new HashMap<String, Object>();
         map.put("title", "三星");
         map.put("img", R.drawable.icon);
         list.add(map);
         return list;
         }  
     
 }
复制代码

案例二
  下面的程序是实现一个带有图片的类表。首先需要定义好一个用来显示每一个列内容的xml,vlist.xml

复制代码
<?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="fill_parent"
        android:layout_height="fill_parent">   
        <ImageView android:id="@+id/img" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="5px"/>
        <LinearLayout android:orientation="vertical"  android:layout_width="wrap_content"  android:layout_height="wrap_content">
            <TextView android:id="@+id/title" android:layout_width="wrap_content" android:layout_height="wrap_content"
                android:textColor="#FFFFFFFF" android:textSize="22px" />
            <TextView android:id="@+id/info"  android:layout_width="wrap_content" android:layout_height="wrap_content"
                android:textColor="#FFFFFFFF" android:textSize="13px" />
        </LinearLayout>
     </LinearLayout>
复制代码
复制代码
public class MyListView3 extends ListActivity {
        // private List<String> data = new ArrayList<String>();
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
     
            SimpleAdapter adapter = new SimpleAdapter(this,getData(),R.layout.vlist,
                    new String[]{"title","info","img"},
                    new int[]{R.id.title,R.id.info,R.id.img});
            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("title", "G1");
            map.put("info", "google 1");
            map.put("img", R.drawable.i1);
            list.add(map);
     
            map = new HashMap<String, Object>();
            map.put("title", "G2");
            map.put("info", "google 2");
            map.put("img", R.drawable.i2);
            list.add(map);
     
            map = new HashMap<String, Object>();
            map.put("title", "G3");
            map.put("info", "google 3");
            map.put("img", R.drawable.i3);
            list.add(map);
             
            return list;
        }
    }
复制代码

4)BaseAdapter

  有时候,列表不光会用来做显示用,我们同样可以在在上面添加按钮。添加按钮首先要写一个有按钮的xml文件,然后自然会想到用上面的方法定义一个适配器,然后将数据映射到布局文件上。但是事实并非这样,因为按钮是无法映射的,即使你成功的用布局文件显示出了按钮也无法添加按钮的响应,这时就要研究一下ListView是如何现实的了,而且必须要重写一个类继承BaseAdapter。下面的示例将显示一个按钮和一个图片,两行字如果单击按钮将删除此按钮的所在行。并告诉你ListView究竟是如何工作的。

vlist2.xml

复制代码
<?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="fill_parent"
        android:layout_height="fill_parent">
        <ImageView android:id="@+id/img" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="5px"/>
        <LinearLayout android:orientation="vertical" android:layout_width="wrap_content" android:layout_height="wrap_content">
           <TextView android:id="@+id/title" android:layout_width="wrap_content" android:layout_height="wrap_content"
                android:textColor="#FFFFFFFF" android:textSize="22px" />
           <TextView android:id="@+id/info" android:layout_width="wrap_content" android:layout_height="wrap_content"
                android:textColor="#FFFFFFFF" android:textSize="13px" />
       </LinearLayout>

       <Button android:id="@+id/view_btn" android:layout_width="wrap_content"  android:layout_height="wrap_content"
            android:text="@string/s_view_btn" android:layout_gravity="bottom|right" />
    </LinearLayout>
复制代码

 

复制代码
/**
002     * @author 
003     *
004     */
005    public class MyListView4 extends ListActivity {
006     
007     
008        private List<Map<String, Object>> mData;
009         
010        @Override
011        public void onCreate(Bundle savedInstanceState) {
012            super.onCreate(savedInstanceState);
013            mData = getData();
014            MyAdapter adapter = new MyAdapter(this);
015            setListAdapter(adapter);
016        }
017     
018        private List<Map<String, Object>> getData() {
019            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
020     
021            Map<String, Object> map = new HashMap<String, Object>();
022            map.put("title", "G1");
023            map.put("info", "google 1");
024            map.put("img", R.drawable.i1);
025            list.add(map);
026     
027            map = new HashMap<String, Object>();
028            map.put("title", "G2");
029            map.put("info", "google 2");
030            map.put("img", R.drawable.i2);
031            list.add(map);
032     
033            map = new HashMap<String, Object>();
034            map.put("title", "G3");
035            map.put("info", "google 3");
036            map.put("img", R.drawable.i3);
037            list.add(map);
038             
039            return list;
040        }
041         
042        // ListView 中某项被选中后的逻辑
043        @Override
044        protected void onListItemClick(ListView l, View v, int position, long id) {
045             
046            Log.v("MyListView4-click", (String)mData.get(position).get("title"));
047        }
048         
049        /**
050         * listview中点击按键弹出对话框
051         */
052        public void showInfo(){
053            new AlertDialog.Builder(this)
054            .setTitle("我的listview")
055            .setMessage("介绍...")
056            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
057                @Override
058                public void onClick(DialogInterface dialog, int which) {
059                }
060            })
061            .show();
062             
063        }
064         
065         
066         
067        public final class ViewHolder{
068            public ImageView img;
069            public TextView title;
070            public TextView info;
071            public Button viewBtn;
072        }
073         
074         
075        public class MyAdapter extends BaseAdapter{
076     
077            private LayoutInflater mInflater;
078             
079             
080            public MyAdapter(Context context){
081                this.mInflater = LayoutInflater.from(context);
082            }
083            @Override
084            public int getCount() {
085                // TODO Auto-generated method stub
086                return mData.size();
087            }
088     
089            @Override
090            public Object getItem(int arg0) {
091                // TODO Auto-generated method stub
092                return null;
093            }
094     
095            @Override
096            public long getItemId(int arg0) {
097                // TODO Auto-generated method stub
098                return 0;
099            }
100     
101            @Override
102            public View getView(int position, View convertView, ViewGroup parent) {
103                 
104                ViewHolder holder = null;
105                if (convertView == null) {
106                     
107                    holder=new ViewHolder(); 
108                     
109                    convertView = mInflater.inflate(R.layout.vlist2, null);
110                    holder.img = (ImageView)convertView.findViewById(R.id.img);
111                    holder.title = (TextView)convertView.findViewById(R.id.title);
112                    holder.info = (TextView)convertView.findViewById(R.id.info);
113                    holder.viewBtn = (Button)convertView.findViewById(R.id.view_btn);
114                    convertView.setTag(holder);
115                     
116                }else {
117                     
118                    holder = (ViewHolder)convertView.getTag();
119                }
120                 
121                 
122                holder.img.setBackgroundResource((Integer)mData.get(position).get("img"));
123                holder.title.setText((String)mData.get(position).get("title"));
124                holder.info.setText((String)mData.get(position).get("info"));
125                 
126                holder.viewBtn.setOnClickListener(new View.OnClickListener() {
127                     
128                    @Override
129                    public void onClick(View v) {
130                        showInfo();                
131                    }
132                });
133                 
134                 
135                return convertView;
136            }
137             
138        }     
139    }
复制代码

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值