ListView实现图文列表:
使用SimpleAdapter建立自定义的列表项:
simpleAdapter 可以用来实现任何我们自己定义的布局。可以使用其实现任何我们自己定义的布局,但是其不能够对内部进行操作,因为 List<Map<String, Object>> list
因为其是通过List ,Map 进项操作的,其内部是封装好的我们只能用其完成数据的填放。
实现图文共现需完成如下步骤:
1:首先我们必须定义一个ListView 让其显示我们需要加载的信息,
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="@+id/listView4"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
然后定义一个列表项的模板 (就是在List的每一个Item中显示的内容样式)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal" >
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" />
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView" />
</LinearLayout>
在主Activity文件中完成 数据源,适配器,等内容。
SimpleAdapter(context, data, resource, from, to);
对于SimpleAdapter 其共有五个参数,第一个参数为上下文, 第二个参数为数据源,第三个参数为承载每一个ListView的Item的模板布局文件。第四个参数为对应关系,对应的map中的那个键值(key)。第五个参数:对应map中数据(values)要显示的信息所对应的的组件(也就是这些组件将显示values)。
Map<String, Object> item1 = new HashMap<String, Object>();
使用Map 存放ListView中每一列的数据,通过put()方法存放相应的键值对。
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
使用List存放多个Map的信息, 然后通过数据适配器将其呈现在ListView中
代码如下:
public class MyActivity4 extends Activity {
private ListView lv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main4);
lv = (ListView) findViewById(R.id.listView4);
Map<String, Object> item1 = new HashMap<String, Object>();
item1.put("image", R.drawable.ic_launcher);
item1.put("name", "小黑");
Map<String, Object> item2 = new HashMap<String, Object>();
item2.put("image", R.drawable.ic_launcher);
item2.put("name", "小白");
Map<String, Object> item3 = new HashMap<String, Object>();
item3.put("image", R.drawable.ic_launcher);
item3.put("name", "小黄");
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
list.add(item1);
list.add(item2);
list.add(item3);
SimpleAdapter sa = new SimpleAdapter(this, list, R.layout.main4_item,
new String[] { "image", "name" }, new int[] { R.id.imageView1,
R.id.textView1 });
lv.setAdapter(sa);
}
}
在模拟器上运行如下显示:
这样就通过Listview完成图文列表项。