2014年12月26日 星期五

介紹 Customed ArrayAdapter

ArrayAdapter在android的使用上,可說是非常廣泛,像是ListView, spinner, Menu, Dialog裡,都可以把ArrayAdapter塞進去,讓使用者看到條列式的資訊


使用時機:
  • 我們要顯示的資料是條列式的
  • 當要顯示的資料類似共通點,如:類似的UI layout,
  • 要顯示的list資料量很多,無法一次顯示(如果一次顯示,performance可能會不好)


我們要去實作的有:
1. 新增在LisView裡的layout : list_item_text.xml

<TextView xmlns:android="http://schemas.android.com/apk/res/android"  
    android:id="@+id/rowTextView"   
    android:layout_width="fill_parent"   
    android:layout_height="wrap_content"  
    android:padding="10dp"  
    android:textSize="16sp" >  
</TextView> 
 
2. ArrayAdapter本身的實作

    private class MyArrayAdapter extends ArrayAdapter<string> {
        private ArrayList<string> data;
        
        // The constructor of ArrayAdapter
        public MyArrayAdapter(Context context, int layoutResourceId, ArrayList<string> 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;
        }
    }
</string></string></string>
3. 建立ArrayAdapter並且顯示

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_array_adapter);
        mListView = (ListView) findViewById(R.id.mainListView);
        
        ArrayList<string> planetList = new ArrayList<string>();  
        planetList.addAll(Arrays.asList(planets) );  
        mListAdapter = new MyArrayAdapter(this, R.layout.list_item_text, planetList);
        mListView.setAdapter(mListAdapter);
    }
</string></string>
參考網站:
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/

下載原始檔