微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Android:关于ListView和SimpleAdapter

我尝试使用SimpleAdapter填充ListView,但仅失败了.

我读过很多案例,但仍然找不到有用的方法.

这是代码.我想知道是什么问题.

ArrayList<HashMap<String,Object>> listdata=new ArrayList<HashMap<String,Object>>();

    for (int i=0;i<3;i++){
        HashMap<String, Object> hm = new HashMap<String, Object>();
        hm.put("title", "title");
        hm.put("context", "context");

        listdata.add(hm);
    }

    String[] from = {"title", "context"};
    int[] to={R.id.title,R.id.context};

    SimpleAdapter adapter = new SimpleAdapter(this, listdata, R.layout.list_item, from, to);
    ListView lv=(ListView)this.findViewById(R.id.listView1);
    lv.setAdapter(adapter);

// list_item的代码

<LinearLayout
<ListView android:layout_height="wrap_content" android:id="@+id/listV1" android:layout_width="match_parent">
<LinearLayout>
<TextView android:layout_height="wrap_content" android:id="@+id/title" android:text="TextView" android:layout_width="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge"></TextView>
<TextView android:text="TextView" android:id="@+id/context" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
</LinearLayout>
</ListView>

如果有人可以提供帮助,我深表感谢!

解决方法:

我怀疑问题出在您的Xml,请尝试为列表项声明第二个布局文件.例如

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

和list_item.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">
    <TextView android:layout_height="wrap_content" android:id="@+id/title" android:text="TextView" android:layout_width="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge"></TextView>
    <TextView android:text="TextView" android:id="@+id/context" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>    
</LinearLayout>

您的代码看起来不错,并且如果使用上述两个布局文件,则可以正常工作.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐