效果图:
逻辑代码
<span style="font-size:18px;">package com.example.listview;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ListView;
import android.widget.SimpleAdapter;
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.listview);
// 创建数据源
int[] images = { R.drawable.pig, R.drawable.pig, R.drawable.pig,
R.drawable.pig, R.drawable.pig, R.drawable.pig, R.drawable.pig,
R.drawable.pig, R.drawable.pig, R.drawable.pig, R.drawable.pig,
R.drawable.pig };
String[] title = { "猪猪侠", "小叮当", "芭比娃娃", "小鲤鱼", "百变小樱", "天空之城", "猪猪侠",
"小叮当", "芭比娃娃", "小鲤鱼", "百变小樱", "天空之城" };
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
// 将图片和文字放入集合中
for (int i = 0; i < images.length; i++) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("images", images[i]);
map.put("title", title[i]);
list.add(map);
}
// 创建适配器
SimpleAdapter adapter = new SimpleAdapter(MainActivity.this, list,
R.layout.item, new String[] { "images", "title" }, new int[] {
R.id.image, R.id.text });
// 绑定适配器
listView.setAdapter(adapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
</span>
布局文件
<span style="font-size:18px;"><RelativeLayout 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" >
<ListView
android:id="@+id/listview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout></span>
<span style="font-size:18px;"><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ImageView
android:id="@+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/pig" />
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:gravity="center" />
</LinearLayout>
</RelativeLayout></span>