arrayAdapter实现的功能很简单,易用,但是ArrayAdapter的功能比较有限,他的每个列表只能是TextView,已将不能满足复杂的列表项,
下面我们学习一下simpleAdapter的使用。
布局文件如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<ListView android:id="@+id/list1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
布局文件中只是定义了一个listView;
java代码如下:
public class MainActivity extends Activity {
private String [] arr1=new String[]{"小明","小强","小芳","小红"};
private String [] arr2=new String[]{"学习好","体育好","唱歌好","语文好"};
private int[] arr3 = new int[]
{R.drawable.ic_launcher,R.drawable.aa,R.drawable.de,R.drawable.dx};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
//创建集合
// List<Map<String,Object>> listItems=new ArrayList<Map<String,Object>>();
List<Map<String,Object>> listItems=new ArrayList<Map<String,Object>>();
for(int i=0;i<arr1.length;i++){
Map<String,Object> listItem=new HashMap<String,Object>();
listItem.put("aa",arr3[i]);
listItem.put("bb", arr1[i]);
listItem.put("cc", arr2[i]);
listItems.add(listItem);
}
//创建一个simpleAdapter
SimpleAdapter simpleAdapter=new SimpleAdapter(this,listItems,R.layout.simple_item,
new String[]{"bb","aa","cc"},
new int[]{R.id.name,R.id.header,R.id.desc});
ListView list=(ListView) findViewById(R.id.list1);
list.setAdapter(simpleAdapter);
}
}
R.layout.simple_item中的布局文件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<ImageView
android:id="@+id/header"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10dp"/>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20dp"
android:textColor="#f0f"
android:paddingLeft="10dp"/>
<TextView
android:id="@+id/desc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20dp"
android:paddingLeft="10dp"/>
</LinearLayout>
</LinearLayout>
将simple_item中的不就文件设置个Adapter,通过simpleAdapter设置个listView显示出来;