Android控件之ListView探究--读取静态xml

http://www.2cto.com/kf/201108/101518.html

在android开发中ListView是比较常用的组件,它以列表的形式展示具体内容,并且能够根据数据的长度自适应显示。

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布局文件

复制代码
  
  
<? 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 = " 20dip " > </ TextView > < TextView android:layout_height = " wrap_content " android:layout_width = " fill_parent " android:id = " @+id/itemText " > </ TextView > </ LinearLayout >
复制代码

LsActivity类

复制代码
  
  
package com.ljq.ls; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import android.app.Activity; import android.os.Bundle; import android.widget.ListView; import android.widget.SimpleAdapter; public class LsActivity extends Activity { private ListView list = null ; public void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); setContentView(R.layout.main); list = (ListView) findViewById(R.id.MyListView); // 组织数据源 List < HashMap < String, String >> mylist = new ArrayList < HashMap < String, String >> (); for ( int i = 0 ;i < 10 ;i ++ ) { HashMap < String, String > map = new HashMap < String, String > (); map.put( " itemTitle " , " This is Title " ); map.put( " itemText " , " This is text " ); mylist.add(map); } // 配置适配器 SimpleAdapter adapter = new SimpleAdapter( this , mylist, // 数据源 R.layout.my_listitem, // 显示布局 new String[] { " itemTitle " , " itemText " }, // 数据源的属性字段 new int [] {R.id.itemTitle,R.id.itemText}); // 布局里的控件id // 添加并且显示 list.setAdapter(adapter); } }
复制代码

运行结果

备注:

1:如果上面的类继承 ListActivity,并且设置 setContentView(R.layout.main); 和 ListView list =(ListView)findViewById(R.id.MyListView); 就会报错,具体原因还不清楚,请有知道的解释下。

2:如果item中包含checkbox或者button,必须设置checkbox或button的 android:focusable="false"否则onListItemClick不响应点击

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值