实现后的效果如下:请忽略铃声音量。。。
其实都好简单,首先建一个包含ListView的布局activity_main:如下
<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" tools:context="com.example.listviewtest.MainActivity" > <ListView android:id="@+id/list_view" android:layout_width="match_parent" android:layout_height="wrap_content"> </ListView> </RelativeLayout>然后再建一个布局,通过这个布局设置ListView中每一项的内容。比如说我这里有一个ImageView,一个显示标题的TextView,和一个显示日期的TextView。我给这个布局取名叫item_layout,如下:
<?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" > <ImageView android:id="@+id/image_view" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_launcher"/> <TextView android:id="@+id/title_textview" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_marginTop="5dp" android:text="标题样式" android:textSize="18sp" android:layout_toRightOf="@id/image_view"/> <TextView android:id="@+id/data_time" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="2015-06-23 12:35" android:textSize="12sp" android:layout_toRightOf="@id/image_view" android:layout_alignBottom="@id/image_view"/> </RelativeLayout>
<pre name="code" class="java">public class MainActivity extends Activity { private ListView myListView; private SimpleAdapter simAdapter; private List<Map<String,Object>> item; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); myListView=(ListView) findViewById(R.id.list_view);\\获得ListView实例 simAdapter=new SimpleAdapter(this, initialData(), R.layout.item_layout, new String[] {"image","title","date"}, new int[]{R.id.image_view,R.id.title_textview,R.id.data_time}); \\创建SimpleAdapter myListView.setAdapter(simAdapter); \\把simpleAdapter配置到ListView } //初始化simpleAdapter每一项的数据,我这里只是随意地设置了一下 public List<Map<String, Object>> initialData(){ item=new ArrayList<Map<String,Object>>(); for(int i=0;i<20;i++){ Map<String, Object> map=new HashMap<String, Object>(); map.put("image", R.drawable.ic_launcher); map.put("title", "标题yangshi"+i); map.put("date", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); item.add(map); } return item; } }
public SimpleAdapter (Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to)
参数: