每次写listview都要翻以前的代码,好烦。所以记下模板,方便下次的使用。
xml文件部分代码:
<ListView android:id="@+id/listview" android:scrollingCache="false" android:cacheColorHint="#00000000" android:divider="@null"
android:listSelector="@android:color/transparent" android:layout_width="fill_parent" android:layout_height="fill_parent" android:fadingEdge="none" android:fadeScrollbars="true"> </ListView>
item的xml布局:(listview_style.xml)
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content"> <TextView android:id="@+id/textview" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="abcd" />
</RelativeLayout>
java 代码:
定义: private ListView m_Listview; private MyAdapter m_listAdapter; private List<Map<String, String>> m_dataList = new ArrayList<Map<String, String>>(); 初始化:
m_listAdapter = new MyAdapter(this,m_dataList);
m_Listview = (ListView) findViewById(R.id.listview);
m_Listview.setAdapter(m_listAdapter);
m_listAdapter.notifyDataSetChanged();
自定义适配器: class MyAdapter extends BaseAdapter{ private Context m_context; //运行上下文 private List<Map<String, String>> m_MapItems ; private LayoutInflater m_listContainer; //视图容器 public final class ListItemView{ //自定义控件集合 TextView tv; } public MyAdapter (Context context ,List<Map<String, String>> MapItems) { // TODO Auto-generated constructor stub this.m_context = context; m_listContainer = LayoutInflater.from(context); //创建视图容器并设置上下文 this.m_MapItems = MapItems; } @Override public int getCount() { // TODO Auto-generated method stub return m_MapItems.size(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub return m_MapItems.get(position); } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub ListItemView listItemView = null; if (convertView == null) { listItemView = new ListItemView(); //获取list_item布局文件的视图 convertView = (View)m_listContainer.inflate(R.layout.listview_style,null); listItemView.tv = (TextView) convertView.findViewById(R.id.textview); convertView.setTag(listItemView); }else { listItemView = (ListItemView)convertView.getTag(); } Map<String, String> map = m_MapItems.get(position); return convertView; } }