package com.example.simpleadapter;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class MainActivity extends Activity {
private ListView lv;
private TextView txtNotice;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtNotice=(TextView) findViewById(R.id.txtNotice);
lv=(ListView) findViewById(R.id.lv);
ArrayList<HashMap<String,Object>> users=new ArrayList<HashMap<String,Object>>();
for(int i=0;i<10;i++){
HashMap<String,Object> user=new HashMap<String, Object>();
user.put("img",R.drawable.img1);
user.put("username", "名字("+i+")");
user.put("age", (11+i)+"");
users.add(user);
}
SimpleAdapter saImageItems=new SimpleAdapter(this,
users,
R.layout.user,
new String[]{"img","username","age"},
new int[]{R.id.img,R.id.txtName,R.id.txtAge}
);
lv.setAdapter(saImageItems);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
txtNotice.setText("你点击了第:"+position+"行!");
}
});
}
}
/********************************************************************************
* 1--使用SimpleAdapter适配器的数据一般都是由--HashMap构成的列表,列表的每一节,对应ListView中的每一行
* 2--通过SimpleAdapter的构造函数,将HashMap每个键的数据映射到布局文件中所对应的控件上
* 3--这个布局文件一般根据自己的需要来自己定义
* ******************************************************************************/
/*************************【梳理一下使用SimpleAdapter适配器的步骤】***********************
* 1--根据需要定义ListView每行所需要实现的布局
* 2--定义一个HaspMap所构成的列表,将以键值对的方式存储在里面
* 3--构造SimpleAdapter适配器的对象
* 4--将ListView绑定到SimpleAdapter适配器上
* ******************************************************************************/
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TableRow
android:id="@+id/tableRow1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<ImageView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:id="@+id/img">
</ImageView>
<TextView
android:id="@+id/txtName"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="#000000"
/>
<TextView
android:id="@+id/txtAge"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="#000000"
/>
</TableRow>
</TableLayout>