2012-11-04 55 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;