3

我想为 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.

看来我应该使用后者。但是我怎样才能调用这个特殊的继承方法呢?

4

2 回答 2

3

你没有。它用 a 覆盖原始文件,UnsupportedOperationException因为它......好吧......不支持。

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

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

于 2012-11-04T04:07:31.580 回答
0

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

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;
于 2013-06-20T15:54:26.137 回答