(1)基本使用实例
<?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/ll1" android:layout_width="match_parent" android:layout_height="wrap_content"> </ListView> </LinearLayout>
定义要实现的item的样式
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal"> <ImageView android:id="@+id/image1" android:layout_width="100dp" android:layout_height="100dp" android:src="@mipmap/ic_launcher" android:layout_margin="5dp"/> <LinearLayout android:id="@+id/ll2" android:layout_width="match_parent" android:layout_height="100dp" android:orientation="vertical" android:layout_marginTop="5dp" android:layout_marginLeft="10dp"> <TextView android:id="@+id/text1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="哈哈" android:textSize="30sp" android:layout_marginTop="10dp"/> <TextView android:id="@+id/text2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="哈哈哈哈哈" android:textSize="24dp" android:layout_marginTop="10dp"/> </LinearLayout> </LinearLayout>
Java文件
package com.example.test3; import android.app.Activity; import android.os.Bundle; import android.widget.ListView; import android.widget.SimpleAdapter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class MainActivity extends Activity{ // 这三个经常是同时出现的 private List<Map<String,Object>> lists; private SimpleAdapter adapter; private ListView listView; // 定义数据 private String[] theme = {"张三","李四","王五"}; private String[] content ={"我是张三,你好","我是李四,你好","我是王五,你好"}; private int[] imageViews = {R.mipmap.ic_launcher,R.mipmap.ic_account,R.mipmap.ic_password}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listView = (ListView) findViewById(R.id.ll1); // 准备数据源 lists = new ArrayList<>(); for(int i = 0;i < theme.length;i++){ Map<String,Object> map =new HashMap<>(); map.put("image",imageViews[i]); map.put("theme",theme[i]); map.put("content",content[i]); lists.add(map); } adapter = new SimpleAdapter(MainActivity.this,lists,R.layout.list_item ,new String[]{"image","theme","content"} ,new int[]{R.id.image1,R.id.text1,R.id.text2}); listView.setAdapter(adapter); } }
效果图: