今天看了下Android 的ArrayAdapter源代码,它继承了BaseAdapter,代码加上注释有500多行。
于是,我精简了下,自己写个了最简单的供大家理解。
1 public class MyArrayAdapter<T> extends BaseAdapter { 2 private List<T> mObjects; 3 private int mResource; 4 private LayoutInflater mInflater; 5 6 public MyArrayAdapter(Context context, int layoutId, List<T> objects) { 7 mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 8 mResource = layoutId; 9 mObjects = objects; 10 } 11 12 @Override 13 public int getCount() { 14 return mObjects.size(); 15 } 16 17 @Override 18 public T getItem(int position) { 19 return mObjects.get(position); 20 } 21 22 @Override 23 public long getItemId(int position) { 24 return position; 25 } 26 27 @Override 28 public View getView(int position, View convertView, ViewGroup parent) { 29 View view; 30 TextView text; 31 32 if (convertView == null) { 33 view = mInflater.inflate(mResource, null); 34 } else { 35 view = convertView; 36 } 37 text = (TextView) view; 38 T item = getItem(position); 39 if (item instanceof CharSequence) { 40 text.setText((CharSequence)item); 41 } else { 42 text.setText(item.toString()); 43 } 44 return view; 45 } 46 }
布局文件可以直接用android系统自带的android.R.layout.simple_list_item_1,里面只有一个TextView。
为了方便理解,我们还是自己动手写一个吧!
1 <?xml version="1.0" encoding="utf-8"?> 2 3 <TextView xmlns:android="http://schemas.android.com/apk/res/android" 4 android:layout_width="match_parent" 5 android:layout_height="wrap_content" 6 android:textSize="24sp" 7 />
然后我们的main.xml,内容如下
1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 android:layout_width="fill_parent" 4 android:layout_height="fill_parent" 5 android:orientation="vertical" > 6 <ListView 7 android:id="@+id/listview" 8 android:layout_width="fill_parent" 9 android:layout_height="wrap_content" 10 /> 11 </LinearLayout>
最后,Activity
1 private ListView listview; 2 3 @Override 4 protected void onCreate(Bundle savedInstanceState) { 5 super.onCreate(savedInstanceState); 6 setContentView(R.layout.main); 7 listview = (ListView)findViewById(R.id.listview); 8 ArrayList<String> data = new ArrayList<String>(); 9 data.add("hello"); 10 data.add("bupt"); 11 12 MyArrayAdapter<String> adapter = new MyArrayAdapter<String>(this, 13 R.layout.item, data); 14 listview.setAdapter(adapter); 15 }
真实的ArrayAdapter比这复杂多了,大家可以自己查看下源代码。