Adapter可以视作控件与数据之间的桥梁
对ListView做自由布局和填充需要使用到Adapter,这里我们采用SimpleAdapter。
简单来说:
1.定义一个ListItem,其数据结构是一个元素为HashMap的ArrayList。
2.填充ListItem
3.使用一个SimpleAdapter将ListItem与Item.xml关联起来
4.将ListView与SimpleAdapter关联起来
逻辑关系用VISO表示如下:
下面是代码:
MainActivity.java
public class MainActivity extends ActionBarActivity { ListView list; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView)findViewById(R.id.list1); ArrayList<HashMap<String , Object>> listItem = new ArrayList<HashMap<String, Object>>();
for(int i=0;i<10;i++){
HashMap<String,Object> map = new HashMap<String,Object>();
map.put("ItemImage",R.drawable.icon);
map.put("ItemTitle",i+"row");
listItem.add(map);
}
SimpleAdapter mSimpleAdapter = new SimpleAdapter(this,listItem,R.layout.item,
new String[]{"ItemImage","ItemTitle","ItemText"},
new int[]{R.id.ItemImage,R.id.ItemTitle,R.id.ItemText});
list.setAdapter(mSimpleAdapter);
}
}
Item.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="fill_parent" android:layout_width="fill_parent">
<ImageView
android:layout_alignParentLeft="true" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/ItemImage"/>
<TextView
android:id="@+id/ItemTitle"
android:layout_toRightOf="@+id/ItemImage"
android:layout_height="wrap_content"
android:layout_width="fill_parent" android:textSize="20sp"/>
<TextView
android:id="@+id/ItemText" android:layout_height="wrap_content"
android:layout_width="fill_parent" android:layout_below="@+id/ItemTitle"/>
</RelativeLayout>