最近在做一个分享笑话的小软件,笑话的名字和内容字体的大小和颜色不一样,而且所有的笑话都放在一个ListView中,那么就需要自定义ListView。
首先,定义每个笑话的样式。标题为灰色,大小为18px;内容为黑色,大小为14px。名字为main3.xml。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#FFFFFF">
<TextView android:id="@+id/storyTitle"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#666666"
android:textSize="18px"
></TextView>
<TextView android:id="@+id/storyContent"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="14px"
android:textColor="#000000"></TextView>
</LinearLayout>
然后,ShowStoryActivity中写入:
private ArrayList<HashMap<String,Object>> mlist=null;
然后将故事的标题和内容读入mlist:
for(int i=0;i<list.size();i++)
{
TbStory tbStory=list.get(i);
HashMap<String,Object> temp=new HashMap<String,Object>();
temp.put("title",tbStory.getTitle());
temp.put("content",tbStory.getContent());
mlist.add(temp);
}
在定义SimpleAdapter:
simAdapter=new SimpleAdapter(this,mlist,R.layout.main3,new String[]{"title","content"},new int[]{R.id.storyTitle,R.id.storyContent});
其中mlist即前面定义的ArrayList<HashMap<String,Object>>,而R.layout.main3即为前面定义的main3.xml,new String[]{"title","content"}即放入mlist的标题和内容的key,而new int[]{R.id.storyTitle,R.id.storyContent}即需写如main3.xml的控件的id号。
再用:
listv.setAdapter(simAdapter);
即可。
效果图如下所示: