欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android入门之ListView应用解析(一)

程序员文章站 2022-11-05 15:49:46
android中的listview是一个经常用到的控件,listview里面的每个子项item可以使一个字符串,也可以是一个组合控件。本文先来说说listview的实现:...

android中的listview是一个经常用到的控件,listview里面的每个子项item可以使一个字符串,也可以是一个组合控件。本文先来说说listview的实现:

1.准备listview要显示的数据;

2.使用 一维或多维 动态数组 保存数据;

3.构建适配器 , 简单地来说, 适配器就是 item数组 , 动态数组 有多少元素就生成多少个item;

4.把 适配器 添加到listview,并显示出来。

接下来,看看本文代码所实现的listview效果:

Android入门之ListView应用解析(一) 

接下来,就开始ui的xml代码:

main.xml代码如下,很简单,也不需要多做解释了:

<?xml version="1.0" encoding="utf-8"?>
<linearlayout 
    android:id="@+id/linearlayout01" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    xmlns:android="http://schemas.android.com/apk/res/android">
    
    <listview android:layout_width="wrap_content" 
         android:layout_height="wrap_content" 
         android:id="@+id/mylistview">
    </listview>
</linearlayout>

my_listitem.xml的代码如下,my_listitem.xml用于设计listview的item:

<?xml version="1.0" encoding="utf-8"?>
<linearlayout 
    android:layout_width="fill_parent" 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical"
    android:layout_height="wrap_content" 
    android:id="@+id/mylistitem" 
    android:paddingbottom="3dip" 
    android:paddingleft="10dip">
    <textview 
        android:layout_height="wrap_content" 
        android:layout_width="fill_parent" 
        android:id="@+id/itemtitle" 
        android:textsize="30dip">
    </textview>
    <textview 
        android:layout_height="wrap_content" 
        android:layout_width="fill_parent" 
        android:id="@+id/itemtext">
    </textview>
</linearlayout>

解释一下,里面用到的一些属性:

1.paddingbottom="3dip",layout往底部留出3个像素的空白区域

2.paddingleft="10dip",layout往左边留出10个像素的空白区域

3.textsize="30dip",textview的字体为30个像素那么大。

最后就是java的源代码:

public void oncreate(bundle savedinstancestate) {
    super.oncreate(savedinstancestate);
    setcontentview(r.layout.main);
    //绑定xml中的listview,作为item的容器
    listview list = (listview) findviewbyid(r.id.mylistview);
    
    //生成动态数组,并且转载数据
    arraylist<hashmap<string, string>> mylist = new arraylist<hashmap<string, string>>();
    for(int i=0;i<30;i++)
    {
     hashmap<string, string> map = new hashmap<string, string>();
     map.put("itemtitle", "this is title.....");
     map.put("itemtext", "this is text.....");
     mylist.add(map);
    }
    //生成适配器,数组===》listitem
    simpleadapter mschedule = new simpleadapter(this, //没什么解释
                       mylist,//数据来源 
                       r.layout.my_listitem,//listitem的xml实现
                       
                       //动态数组与listitem对应的子项    
                       new string[] {"itemtitle", "itemtext"}, 
                       
                       //listitem的xml文件里面的两个textview id
                       new int[] {r.id.itemtitle,r.id.itemtext});
    //添加并且显示
    list.setadapter(mschedule);
}