2012-11-04 56 views
3

我想爲GridView添加頁腳視圖。addView for GridView

我在文檔中發現GridView有2個繼承了的addView(查看子)方法。

From class android.widgetAdapterView 

void addView(View child) 

This method is not supported and throws an UnsupportedOperationException when called. 

From class android.view.ViewGroup 

void addView(View child) 

Adds a child view. 

看來我應該使用後者。但是我怎樣才能調用這個特定的繼承方法?

回答

3

你不知道。它用UnsupportedOperationException覆蓋原來的,因爲它是..好..不支持。

您應該編輯適配器。根據您的實施情況,這看起來會有所不同。但是,您只需向適配器添加更多數據,並在適配器上調用.notifyDataSetChanged(),並且您的GridView將自行添加視圖。

在您的GridView之後,頁腳視圖應該是單獨的View,或者您必須保持其在適配器列表中的位置,以便在添加新項目時始終保持最終狀態。

+0

將它添加到適配器似乎很酷。但是footview肯定會比gridview中的其他項目更寬。任何方式來處理這個? – onemach

+0

在這種情況下,您將不得不使用自定義適配器。然後檢查,如果'位置== items.length - 1',然後膨脹更廣泛的'視圖'。 – Eric

+0

我的意思是腳的視圖應該佔據一排。而其他行有3個項目。如何才能做到這一點? – onemach

0

提供了埃裏克斯解決方案爲例,該適配器可以保持跟蹤「頁腳」的 位置兩個額外的成員,它的事件處理程序:

class ImageViewGridAdapter : ArrayAdapter<int> 
{ 
    private readonly List<int> images; 

    public int EventHandlerPosition { get; set; } 
    public EventHandler AddNewImageEventHandler { get; set; } 

    public ImageViewGridAdapter(Context context, int textViewResourceId, List<int> images) 
     : base(context, textViewResourceId, images) 
    { 
     this.images = images; 
    } 

    public override View GetView(int position, View convertView, ViewGroup parent) 
    { 
     ImageView v = (ImageView)convertView; 

     if (v == null) 
     { 
      LayoutInflater li = (LayoutInflater)this.Context.GetSystemService(Context.LayoutInflaterService); 
      v = (ImageView)li.Inflate(Resource.Layout.GridItem_Image, null); 

      // ** Need to assign event handler in here, since GetView 
      // is called an arbitrary # of times, and the += incrementor 
      // will result in multiple event fires 

      // Technique 1 - More flexisble, more maintenance //////////////////// 
      if (position == EventHandlerPosition)    
       v.Click += AddNewImageEventHandler; 

      // Technique 2 - less flexible, less maintenance ///////////////////// 
      if (position == images.Count) 
       v.Click += AddNewImageEventHandler; 
     } 

     if (images[position] != null) 
     { 
      v.SetBackgroundResource(images[position]); 
     } 

     return v; 
    } 
} 

然後,將該適配器分配到前柵格查看,只是分配這些值(位置不一定是結束,但對於一個頁腳它應該是):

List<int> images = new List<int> { 
    Resource.Drawable.image1, Resource.Drawable.image2, Resource.Drawable.image_footer 
}; 

ImageViewGridAdapter recordAttachmentsAdapter = new ImageViewGridAdapter(Activity, 0, images); 

recordAttachmentsAdapter.EventHandlerPosition = images.Count; 
recordAttachmentsAdapter.AddNewImageEventHandler += NewAttachmentClickHandler; 

_recordAttachmentsGrid.Adapter = recordAttachmentsAdapter;