标签:android style blog http io color os ar 使用
会当凌绝顶,一览众山小。 —— 杜 甫《望岳》
本讲内容:ListView列表组件 与 Adapter适配器的用法
一、ListView使用SimpleAdapter
很多时候需要在列表中展示一些除了文字以外的东西,比如图片等。这时候可以使用SimpleAdapter。可以通过它
使用simpleAdapter的数据一般都是用HashMap构成的列表,列表的每一节对应ListView的每一行。通过SimpleAdapter的构造函数,将HashMap的每个键的数据映射到布局文件中对应控件上。这个布局文件一般根据自己的需要来自定义ListView中的item的内容,比如图片、多选框等。
二、使用SimpleAdapter的步骤。
(1)根据需要定义ListView每行所实现的布局。
(2)定义一个HashMap构成的列表,将数据以键值对的方式存放在里面。
(3)构造SimpleAdapter对象。
(4)将LsitView绑定到SimpleAdapter上。
我们通过下面例子感受一下,代码的讲解都写在注释里了
下面是res/layout/activity_main.xml 布局文件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.text.MainActivity$PlaceholderFragment" >
<ListView
android:id="@+id/listViewId"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:id="@+id/ItemImageId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"/>
<TextView
android:id="@+id/ItemTitleId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:textColor="#ff00ff"/>
<TextView
android:id="@+id/ItemTextId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:textColor="#ffff00"
android:layout_below="@+id/ItemTitleId"/>
</RelativeLayout>
public class MainActivity extends Activity {
private ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listViewId);
// 定义一个动态数组
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.ic_launcher);
map.put("ItemTitle", "第" + i + "行");
map.put("ItemText", "这是第" + i + "行");
listItem.add(map);
}
SimpleAdapter adapter = new SimpleAdapter(this, listItem,R.layout.item, new String[] { "ItemImage",
"ItemTitle","ItemText" }, new int[] { R.id.ItemImageId,R.id.ItemTitleId, R.id.ItemTextId});
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?>parent, View view,int position, long id) {
//点击后在标题上显示点击了第几行
setTitle("你点击了第"+position+"行");
}
});
}
标签:android style blog http io color os ar 使用
原文地址:http://blog.csdn.net/liguojin1230/article/details/40685115