在线咨询
QQ咨询
服务热线
服务热线:13125520620
TOP

ListView的基本用法

发布时间:2018-5-16 浏览:3127

Listview简介
 
  安卓UI要想实现一个功能稍微复杂一点的功能,势必要用到Listview,它可以实现最常用的数据到视图的映射,显示动态的页面。
 
  说到listview就肯定要说到adapter,因为我们是实现最基本的功能,所以这里采用简单的SimpleAdapter。
 
实例演示
 
  下面我们实现一个简单的显示历史记录的页面。
 
  首先是要有数据,如果初学者对操作SQLlite不熟悉的话(当然就是我懒),推荐常用的另一种数据存储方式:android.content.SharedPreferences,看这个类的名字“共享的偏好项”就可以知道,它主要是用来存储app中用户的一些偏好项的,和windows的ini文件类似。
 
   sharedpreferences是非常轻量级的存储方式,它在启动时会将所有的数据加载进内存,所以只适合数据量不是很大时使用,它将数据以key-value的形式存储在/data/data/包名/shared_prefs/文件名.xml中。
 
  先来一波sharedpreferenced的基本操作:
 
//存储一条记录
private void saveReacord(){
    //将基本信息转化为json字符串
    String curRecordString = GsonTools.createJsonString(currentRecord);
    //用存储历史数据
    SharedPreferences history=getApplicationContext().getSharedPreferences("HISTORY", MODE_APPEND);
    //先拿到编辑器
    Editor editor = history.edit();
    //用存储的时间秒值作为一条记录的主键
    editor.putString(currentRecord.getTime(), curRecordString);
    editor.commit();                                        
}
 
这样存储进去后就会在对应路径下生成一个HISTORY.xml文件,那里的模式可以选如下几种:
 
Context.MODE_PRIVATE :只被本地程序读写。
Context.MODE_WORLD_READABLE :能被其他程序读。
Context.MODE_WORLD_WRITEABLE :能被其他程序读、写。
Context.MODE_APPEND:打开后追加到末尾
sharepreferences的常用方法有如下几种:
 
boolean contans(String key) :判断SharedPreferences中是否包含特定key的数据。
abstract Map
编辑器的操作有以下几种:
 
clear() :清空SharedPreferences里所有数据。
putXxx(String key, xxx value) :向SharedPreferences中写入数据。
remove(String key) :删除SharedPreferences中指定key的值。
commit() :当Editor编辑完,该方法提交修改。
那么现在就可以自己向里面put点数据了,至此数据已经有了。
 
  下面就开始布局页面了。我们在layout下新建一个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="#FF000000"
            android:textSize="30px" />
        <TextView android:id="@+id/info" 
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" 
            android:textColor="#FF000000"
            android:textSize="20px" />
    </LinearLayout>
</LinearLayout>
 
  这就是listview中的一条记录的模样,就是左边一个图像,右边两行文字。
 
  接下来就是写最重要的Activity了。写listview最简单的做法就是直接继承ListActivity,且看代码:
 
public class ListViewDemoActivity extends ListActivity {
 
    private List<Map<String, Object>> adaptorList = null;
    private SimpleAdapter adapter = null;
    private int currentPosition = -1;// 当前选中的记录的下标
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
 
        adaptorList = new ArrayList<Map<String, Object>>();
        adapter = new SimpleAdapter(this, getData(), R.layout.vlist, new String[] { "time", "path", "img" },
                new int[] { R.id.title, R.id.info, R.id.img });
        setListAdapter(adapter);
 
        // 为所有列表项注册上下文菜单  步骤一
        this.registerForContextMenu(getListView());
 
    }
 
    private List<Map<String, Object>> getData() {
        SharedPreferences history = getApplicationContext().getSharedPreferences("HISTORY", MODE_PRIVATE);
        Map<String, ?> historys = history.getAll();
        Map<String, Object> items = null;
        if (historys != null && historys.size() != 0) {
            for (String time : historys.keySet()) {
                String value = (String) historys.get(time);
                Log.v("value", value);
                String path = value.substring(value.lastIndexOf(',') + 1);
                Log.v("path", path);
                String info = value.substring(0, value.lastIndexOf(','));
                Log.v("info", info);
                items = new HashMap<String, Object>();
                items.put("time", time);
                items.put("info", info);
                items.put("path", path);
                items.put("img", R.drawable.cd);
                adaptorList.add(items);
            }
        }
        //对读取到的数据进行排序
        Collections.sort(adaptorList, new Comparator<Map<String, Object>>() {
 
            @Override
            public int compare(Map<String, Object> lhs, Map<String, Object> rhs) {
                return ((String) lhs.get("time")).compareTo((String) rhs.get("time"));
            }
        });
        return adaptorList;
    }
 
    //步骤二
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        Log.v("menu", "populate context menu");
        //菜单标题
        menu.setHeaderTitle("选择操作");
        //菜单选项
        menu.add(0, 1, Menu.NONE, "上传");
        menu.add(0, 2, Menu.NONE, "查看信息");
        menu.add(0, 3, Menu.NONE, "删除");
    }
 
    // 上下文菜单的响应 //步骤三
    @Override
    public boolean onContextItemSelected(MenuItem item) {
        // 得到当前被选中的item在listview中的信息
        AdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo) item.getMenuInfo();
        Log.v("menuitem", "在listview中的position:" + menuInfo.position);// 
        Log.v("menuitem", "在菜单项中的id:" + item.getItemId());// 
 
        // 将当前选中的position记录到全局变量
        currentPosition = menuInfo.position;
 
        switch (item.getItemId()) {
        case 1:
            break;
        case 2:
            break;
        case 3:
            // 删掉长按的item
            deleteRecord();
            Toast.makeText(getApplicationContext(), "删除成功", Toast.LENGTH_SHORT).show();
            break;
        default:
            return super.onContextItemSelected(item);
        }
        return true;
    }
 
    /**
     * 删除一条记录
     * 
     * @param curPosition 在list中的下标
     * @param curItem 当前item里面的Map
     */
    private void deleteRecord() {
        if (currentPosition >= 0) {
            Map<String, ?> curItem = adaptorList.get(currentPosition);
            // 删除SharePreference里面的记录
            SharedPreferences historys = this.getSharedPreferences("HISTORY", MODE_APPEND);
            Editor editor = historys.edit();
            editor.remove((String) curItem.get("time"));
            editor.commit();
            // 删除list中的记录
            adaptorList.remove(currentPosition);
            // 删除对应录音文件
            if (curItem.get("path") != null) {
                new File((String) curItem.get("path")).delete();
            }
            // 动态更新listview
            adapter.notifyDataSetChanged();
 
            currentPosition = -1;
        } else {
            Toast.makeText(getApplicationContext(), "请重试", Toast.LENGTH_SHORT).show();
        }
    }
}
 
对以上代码的解释:
 
adapter? 
简单来说就是适配映射,首先要有数据List< Map>,然后将Map中的对应项映射到vlist布局当中的对应地方去。
操作listview的每一项? 
这里我采用的是长按跳上下文菜单的方法。上下文菜单操作步骤: 
1.给每个item项注册上下文菜单:代码中步骤一
 
2.添加菜单项:代码中步骤二
 
3.添加菜单的响应:代码中步骤三,要注意的是可以通过传过来的MenuItem对象得到很多有用的信息,包括当前对象在list中的position。
 
(删除后)动态更新:adapter.notifyDataSetChanged();
 

TAG
软件定制,软件开发,瀚森HANSEN
0
该内容对我有帮助