simpleAdapter是最基本也是最常用的,虽然可以实现自己的adapter(baseadapter等),但是比较复杂而且没有必要。
package com.cn.demo05vitamio; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import android.widget.SimpleAdapter; public class MainActivity extends ActionBarActivity { private ListView lView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); lView = (ListView)findViewById(R.id.list); lView.setAdapter(new SimpleAdapter(this, getdata(), R.layout.mylist_item, new String[]{"title",}, new int[]{R.id.text1})); lView.setOnItemClickListener(new OnItemClickListener() { @SuppressWarnings("unchecked") @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Map<String, Object> map = (Map<String, Object>)parent.getItemAtPosition(position); Intent intent =(Intent)map.get("intent"); startActivity(intent); } }); } private List<Map<String, Object>> getdata() { List<Map<String, Object>> myData = new ArrayList<Map<String,Object>>(); addItem(myData,"title01",new Intent(this, Demo01.class)); addItem(myData,"ttile02",new Intent(this, Demo02.class)); return myData; } private void addItem(List<Map<String, Object>> myData, String string, Intent intent) { Map<String, Object> map = new HashMap<String, Object>(); map.put("title", string); map.put("intent", intent); myData.add(map); } }
布局文件R.layout.mylist_item可以自己随意定义样式。
时间: 2024-11-14 12:25:30