addView for GridView

时间:2012-11-04 03:50:23

标签: java android inheritance

我想为GridView添加页脚视图。

我在文档中发现GridView有2个继承的 addView(View child)方法。

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.

似乎我应该使用后者。但是如何调用这个特定的继承方法呢?

2 个答案:

答案 0 :(得分:3)

你不是。它会用UnsupportedOperationException覆盖原文,因为它很好..不支持。

您应该编辑适配器。根据您的实施情况,这看起来会有所不同。但是,您只需向适配器添加更多数据,并在适配器上调用.notifyDataSetChanged()GridView将自行添加视图。

页脚视图应该是View之后的单独GridView,或者您必须在适配器列表中保持其位置,以便在添加新项目时始终为最后一个。

答案 1 :(得分:0)

提供Erics解决方案的示例,适配器可以维护两个额外的成员来跟踪 “页脚”的位置及其事件处理程序:

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;