本案例学习来自 _鸿洋_ 大神,自己在写一遍,加深记忆
我们都是以前写listView 都是这个样子
1 package com.example.listviewdemo; 2 3 import java.util.ArrayList; 4 import java.util.List; 5 6 import android.app.Activity; 7 import android.os.Bundle; 8 import android.widget.ListView; 9 10 public class MainActivity extends Activity {11 12 private ListView lv ;13 private Listlist = new ArrayList ();14 15 @Override16 protected void onCreate(Bundle savedInstanceState) {17 super.onCreate(savedInstanceState);18 setContentView(R.layout.activity_main);19 initData();20 lv = (ListView) findViewById(R.id.id_main_lv);21 MyAdapter adapter = new MyAdapter (list,this);22 lv.setAdapter(adapter);23 }24 25 private void initData() {26 for(int i=0;i<30;i++){27 list.add("qqqqq"+i);28 }29 }30 31 32 }
16 7 12 13
1 package com.example.listviewdemo; 2 3 import java.util.List; 4 5 import android.content.Context; 6 import android.view.View; 7 import android.view.ViewGroup; 8 import android.widget.BaseAdapter; 9 import android.widget.TextView;10 11 public class MyAdapterextends BaseAdapter {12 13 private List list;14 private Context mContext;15 public MyAdapter(List list,Context mContext) {16 super();17 this.list = list;18 this.mContext = mContext;19 }20 21 22 @Override23 public int getCount() {24 // TODO Auto-generated method stub25 return list.size();26 }27 28 @Override29 public Object getItem(int position) {30 // TODO Auto-generated method stub31 return list.get(position);32 }33 34 @Override35 public long getItemId(int position) {36 // TODO Auto-generated method stub37 return position;38 }39 40 @Override41 public View getView(int position, View convertView, ViewGroup parent) {42 43 ViewHolder holder = null;44 if(convertView == null){45 holder = new ViewHolder();46 convertView = View.inflate(mContext, R.layout.item_listview, null);47 holder.tv = (TextView) convertView.findViewById(R.id.item_tv);48 convertView.setTag(holder);49 }else{50 holder = (ViewHolder) convertView.getTag();51 }52 holder.tv.setText((String)list.get(position));53 System.out.println((String)list.get(position));54 return convertView;55 }56 57 class ViewHolder{58 TextView tv ;59 }60 }
1 27 8 13 14