使用時機:
- 我們要顯示的資料是條列式的
- 當要顯示的資料類似共通點,如:類似的UI layout,
- 要顯示的list資料量很多,無法一次顯示(如果一次顯示,performance可能會不好)
我們要去實作的有:
1. 新增在LisView裡的layout : list_item_text.xml
2. ArrayAdapter本身的實作
3. 建立ArrayAdapter並且顯示private class MyArrayAdapter extends ArrayAdapter { private ArrayList data; // The constructor of ArrayAdapter public MyArrayAdapter(Context context, int layoutResourceId, ArrayList data) { super(context, layoutResourceId); this.data = data; } // How many items are in the data set represented by this Adapter @Override public int getCount() { return data.size(); } // Get a View that displays the data at the specified position in the data set @Override public View getView(int position, View convertView, ViewGroup parent) { View view; if (convertView == null) { LayoutInflater inflater = ((Activity) this.getContext()).getLayoutInflater(); view = inflater.inflate(R.layout.list_item_text, parent, false); } else { view = convertView; } TextView text; text = (TextView) view.findViewById(R.id.rowTextView); text.setText(data.get(position)); return view; } }
參考網站:@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_my_array_adapter); mListView = (ListView) findViewById(R.id.mainListView); ArrayList planetList = new ArrayList (); planetList.addAll(Arrays.asList(planets) ); mListAdapter = new MyArrayAdapter(this, R.layout.list_item_text, planetList); mListView.setAdapter(mListAdapter); }
http://developer.android.com/reference/android/widget/ArrayAdapter.html
http://windrealm.org/tutorials/android/android-listview.php
https://devtut.wordpress.com/2011/06/09/custom-arrayadapter-for-a-listview-android/
下載原始檔