您的位置:首页 > 其它

ListView之SimpleAdapter

2016-03-08 15:27 190 查看
SimpleAdapter是安卓内置的适配器,本文展示的是listview的子项为{图片,文件}组合

如下图所示:



具体代码:

SimpleAdapter_test.java

/*
ListView :列表
通常有两个职责:
a.将数据填充到布局
b.处理点击事件

一个ListView创建需要几个元素:
a.ListView中第一列的    View
b.填入View的图片或数据
c.连接数据 与ListView的适配器

有哪些适配器?
ArrayAdapter<T>  用来绑定一个数组,支持泛型设计
SimpleAdapter 用来绑定在xml中定义的控件和对应的数据
SimpleCursorAdapter:用来绑定游标得到的数据
BaseAdapter 通用的基础适配器

*
* */
public class SimpleAdapter_test extends Activity {

private ListView listview;
private int[] ids=new int[]{
R.drawable.s1,
R.drawable.s2,
R.drawable.s3,
R.drawable.s4,
R.drawable.s5};

private SimpleAdapter adapter;
private Context context;
private List<Map<String,Object>> datas;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.baseadapate);
context = this;
listview = (ListView) findViewById(R.id.listview);

initData();
//map中所有的key的
String[] from=new String[]{"map_image","map_content"};
int[] to=new int[]{R.id.image,R.id.content};
adapter=new SimpleAdapter(context, datas, R.layout.items2, from, to);

listview.setAdapter(adapter);

listview.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {

Toast.makeText(context,"你选中的是:"+ datas.get(position).get("map_content"), 0).show();
}
});

}

private void initData() {

datas = new ArrayList<Map<String,Object>>();
for(int i=0;i<5;i++)
{
Map<String,Object> map = new HashMap<String, Object>();
map.put("map_image",BitmapFactory.decodeResource(getResources(), ids[i]));
map.put("map_content", "hahacontent"+i);
datas.add(map);
}
}

}


baseadapate.xml

<?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:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/listview"
>

</ListView>

</LinearLayout>


items2.xml

<?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="horizontal"
android:layout_gravity="center"

>

<ImageView
android:id="@+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/ic_launcher"
/>

<TextView
android:layout_marginTop="15dp"
android:id="@+id/content"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="haa"

/>

</LinearLayout>


不要忘了在清单里注册activity,并且设置为app入口

<activity android:name=".BaseAdapter_test">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: