当前位置: 代码迷 >> Android >> 稳扎稳打_Android开发课[19]_用户界面之ListView(列表视图)
  详细解决方案

稳扎稳打_Android开发课[19]_用户界面之ListView(列表视图)

热度:115   发布时间:2016-04-28 01:36:12.0
步步为营_Android开发课[19]_用户界面之ListView(列表视图)

Focus on technology, enjoy life!—— QQ:804212028
浏览链接:http://blog.csdn.net/y18334702058/article/details/44624305


  • 主题:用户界面之ListView(列表视图)
    -ListView和TextView,Button等控件一样,一样的定义方式。但是Android开发中说道ListView就不得不说Adapter适配器,因为只有通过Adapter才可以把列表中的数据映射到ListView中。

创建一个ListView需要3个元素

(1)ListView中的每一列的View。
(2)填入View的数据或者图片等。
(3)连接数据与ListView的适配器。

常用适配器

Adapter 含义
ArrayAdapter 用来绑定一个数组,支持泛型操作
SimpleAdapter 用来绑定在xml中定义的控件对应的数据
SimpleCursorAdapter 用来绑定游标得到的数据
BaseAdapter 通用的基础适配器

ListView结合ArrayAdapter适配器使用

activity_main.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"    >    <ListView         android:id="@+id/listView"        android:layout_width="fill_parent"        android:layout_height="wrap_content"    /></LinearLayout>

MainActivity.java源代码:

import android.app.Activity;import android.os.Bundle;import android.view.View;import android.widget.AdapterView;import android.widget.AdapterView.OnItemClickListener;import android.widget.ArrayAdapter;import android.widget.ListView;import android.widget.Toast;public class MainActivity extends Activity {    private ListView listView;    String[] str= new String[]{"aa","bb","cc","dd","ee"};    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        listView = (ListView)findViewById(R.id.listView);        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, str);;        //上面android.R.layout.simple_list_item_1是系统自带的一种ListView布局方式        listView.setAdapter(adapter);        listView.setOnItemClickListener(new OnItemClickListener(){            @Override            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,                    long arg3) {                // TODO Auto-generated method stub                Toast.makeText(MainActivity.this, "你点击的是"+arg2, Toast.LENGTH_LONG).show();            }                   });    }}

运行结果:

这里写图片描述

ListView结合SimpleAdapter适配器使用

难道我们只满足在列表中只展示几个文字吗?我们向更加漂亮点,我们想在列表中加入图片。这时候使用SimpleAdapter的时候到了。SimpleAdapter的使用也非常简单,同时它的功能也非常强大。可以通过它自定义ListView中的item(item就是列表每一行的显示)的内容,比如图片、多选框等。看一个例子,实现一个每一行都有一个ImageView和TextView的ListView。

activity_main.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"    >    <ListView         android:id="@+id/listView"        android:layout_width="fill_parent"        android:layout_height="wrap_content"    /></LinearLayout>

定义一个item的显示布局,也就是列表每一行怎么显示,来看源代码
item.xml源代码:

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent">    <ImageView        android:id="@+id/ItemImage"        android:layout_alignParentRight="true"         android:layout_width="wrap_content"        android:layout_height="wrap_content" />     <TextView        android:id="@+id/ItemTitle"         android:layout_height="wrap_content"         android:layout_width="fill_parent"         android:textColor="#336699"        android:textSize="20sp"/>     <TextView         android:id="@+id/ItemText"          android:layout_height="wrap_content"         android:layout_width="fill_parent"         android:textColor="#336699"        android:layout_below="@+id/ItemTitle"/> </RelativeLayout>

MainActivity.java源代码:

import java.util.ArrayList;import java.util.HashMap;import android.app.Activity;import android.os.Bundle;import android.view.View;import android.widget.AdapterView;import android.widget.AdapterView.OnItemClickListener;import android.widget.ListView;import android.widget.SimpleAdapter;import android.widget.Toast;public class MainActivity extends Activity {    private ListView listView;    private String[] mListTitle = { "姓名", "性别", "年龄", "居住地","邮箱"};      private String[] mListStr = { "aa","bb","cc","dd","ee" };    ArrayList<HashMap<String, Object>> itemData = new ArrayList<HashMap<String,Object>>();    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        listView = (ListView)findViewById(R.id.listView);        for(int i=0;i<mListTitle.length;i++){            HashMap<String,Object> item = new HashMap<String,Object>();            item.put("image", R.drawable.myimage);              item.put("title", mListTitle[i]);              item.put("text", mListStr[i]);              itemData.add(item);          }        SimpleAdapter adapter = new SimpleAdapter(this, itemData, R.layout.item, new String[] {"image"                ,"title", "text"}, new int[] {R.id.ItemImage,R.id.ItemTitle,R.id.ItemText});        listView.setAdapter(adapter);        listView.setOnItemClickListener(new OnItemClickListener(){            @Override            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,                    long arg3) {                // TODO Auto-generated method stub                Toast.makeText(MainActivity.this, "你点击的是"+arg2, Toast.LENGTH_LONG).show();            }                   });    }}

运行结果:

这里写图片描述

ListView结合BaseAdapter适配器使用

其实开发中最常用的还是BaseAdapter,尽管使用起来比其他适配器有些麻烦,但是使用它却能实现很多自己喜欢的列表布局,比如ListView、GridView、Gallery、Spinner等。它是直接继承自接口类Adapter的,使用BaseAdapter时需要重写很多方法,其中最重要的当属getView。

activity_main.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"    >    <ListView         android:id="@+id/listView"        android:layout_width="fill_parent"        android:layout_height="wrap_content"    /></LinearLayout>

item.xml源代码:

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent">    <ImageView        android:id="@+id/ItemImage"        android:layout_alignParentLeft="true"         android:layout_width="wrap_content"        android:layout_height="wrap_content" />     <TextView        android:id="@+id/ItemTitle"         android:layout_height="wrap_content"         android:layout_width="fill_parent"         android:layout_toRightOf="@id/ItemImage"        android:textColor="#336699"        android:textSize="20sp"/>     <TextView         android:id="@+id/ItemText"          android:layout_height="wrap_content"         android:layout_width="fill_parent"         android:layout_toRightOf="@id/ItemImage"        android:textColor="#336699"        android:layout_below="@+id/ItemTitle"/>      <Button         android:id="@+id/ItemButton"        android:layout_alignParentRight="true"         android:layout_width="wrap_content"        android:layout_height="wrap_content" /></RelativeLayout>

MainActivity.java源代码:

import java.util.ArrayList;import java.util.HashMap;import android.app.Activity;import android.content.Context;import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.View.OnClickListener;import android.view.ViewGroup;import android.widget.AdapterView;import android.widget.AdapterView.OnItemClickListener;import android.widget.BaseAdapter;import android.widget.Button;import android.widget.ImageView;import android.widget.ListView;import android.widget.TextView;import android.widget.Toast;public class MainActivity extends Activity {    private ListView listView;    private ArrayList<HashMap<String, Object>> data;    private String[] mListTitle = { "姓名", "性别", "年龄", "居住地","邮箱"};      private String[] mListStr = { "aa","bb","cc","dd","ee" };    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        //获取将要绑定的数据设置到data中        data = getData();        listView = (ListView)findViewById(R.id.listView);        MyAdapter adapter = new MyAdapter(this);        listView.setAdapter(adapter);            }    private ArrayList<HashMap<String, Object>> getData(){         ArrayList<HashMap<String, Object>> itemDate = new ArrayList<HashMap<String,Object>>();        /**为动态数组添加数据*/            for(int i=0;i<mListTitle.length;i++){        HashMap<String,Object> item = new HashMap<String,Object>();           item.put("ItemImage", R.drawable.myimage);             item.put("ItemTitle", mListTitle[i]);             item.put("ItemText", mListStr[i]);             itemDate.add(item);         }        return itemDate;    }    private class MyAdapter extends BaseAdapter{    private LayoutInflater mInflater;    public MyAdapter(Context context){        this.mInflater = LayoutInflater.from(context);    }    @Override    public int getCount() {        // TODO Auto-generated method stub        return getData().size();//返回列表的行数    }    @Override    public Object getItem(int arg0) {        // TODO Auto-generated method stub        return null;    }    @Override    public long getItemId(int arg0) {        // TODO Auto-generated method stub        return 0;    }    @Override    public View getView(final int position, View convertView, ViewGroup parent) {        // TODO Auto-generated method stub        ViewHolder holder;        if(convertView == null){            holder = new ViewHolder();            convertView = mInflater.inflate(R.layout.item, null);            holder.imageView = (ImageView)convertView.findViewById(R.id.ItemImage);            holder.title = (TextView)convertView.findViewById(R.id.ItemTitle);            holder.text = (TextView)convertView.findViewById(R.id.ItemText);            holder.bt = (Button)convertView.findViewById(R.id.ItemButton);            //将设置好的布局保存到缓存中,并将其设置在Tag里,以便后面方便取出Tag            convertView.setTag(holder);        }        else{            holder = (ViewHolder)convertView.getTag();        }        /**设置TextView显示的内容,即我们存放在动态数组中的数据*/                    holder.title.setText((String)data.get(position).get("ItemTitle"));        holder.text.setText((String)data.get(position).get("ItemText"));        holder.imageView.setImageResource((Integer)data.get(position).get("ItemImage"));        /**为Button添加点击事件*/                     holder.bt.setOnClickListener(new OnClickListener() {            public void onClick(View v) {                Toast.makeText(MainActivity.this, "你点击了---"+ position +"---按钮", Toast.LENGTH_LONG).show();            }        });        return convertView;        }    }    public final class ViewHolder{        public TextView title;        public TextView text;        public Button   bt;        public ImageView imageView;    }}

运行结果:

这里写图片描述

Focus on technology, enjoy life!—— QQ:804212028
浏览链接:http://blog.csdn.net/y18334702058/article/details/44624305

  相关解决方案