在Android画廊中显示空视图

3

大家好 -

我正在尝试实现一个显示图像ArrayList的画廊小部件,并从开发网站上的Hello, Gallery示例开始。这部分已经很好地实现了。

我需要让画廊显示一个空视图(当ArrayList没有内容时的特殊视图),但我似乎无法让画廊这样做。我过去曾在ListView和其他AdapterViews中这样做,但我无法让它在Gallery中工作。我需要在Adapter、Gallery或两者中重写/实现什么来显示空视图?这是我的适配器代码:

public class ImageAdapter extends BaseAdapter {

     int mGalleryItemBackground;
     private Context mContext;
     private ArrayList<Drawable> images;

     public ImageAdapter(Context c) {
      mContext = c;
      TypedArray a = c.obtainStyledAttributes(R.styleable.Gallery1);
      mGalleryItemBackground = a.getResourceId(R.styleable.Gallery1_android_galleryItemBackground, 0);
      a.recycle();

      images = new ArrayList<Drawable>();
     }

     public void addImage(Drawable d) {
      images.add(d);
     }

     public boolean isEmpty() {
      return getCount() == 0;
     }

     public int getCount() {
      return images.size();
     }

     public Drawable getItem(int position) {
      return images.get(position);
     }

     public long getItemId(int position) {
      return position;
     }

     public View getView(int position, View contentView, ViewGroup parent) {
      ImageView i = new ImageView(mContext);
      i.setImageDrawable(images.get(position));

      i.setLayoutParams(new Gallery.LayoutParams(160, 120));
      i.setScaleType(ImageView.ScaleType.FIT_XY);
      i.setBackgroundResource(mGalleryItemBackground);

      return i;
     }
}

当使用空的ArrayList展示视图时,getCount()方法会被调用(返回0),但是Gallery从未检查isEmpty,当我在Gallery中定义了getEmptyView()时,它也从未被调用。我是否错过了BaseAdapter中另一个必需的方法以正确通知空状态?
谢谢!

附言:我找到了setEmptyView(View emptyView)方法(糟糕),这个方法允许我在我的画廊上设置一个视图,这个视图应该在空ArrayList时显示,并且现在适配器的空状态是被检查的,但是视图仍然没有显示!有什么想法或思考吗? - devunwired
1个回答

1

通过这篇文章的帮助,我找到了答案:

AdapterView中setEmtpyView的正确使用方法

问题的关键在于(一旦我让Gallery/AdapterView使用补充信息正确调用空状态检查),AdapterView只设计用于在内容视图和空视图之间切换视图可见性设置(交换View.GONE和View.VISIBLE)。因此,如果您没有做好在父布局中正确创建和布局内容视图和空视图的工作,它们将无法正确显示。

在我的情况下,我以编程方式创建了空视图(只是一个TextView),并使用setEmptyView()将其附加到适配器视图。TextView从未附加到代表Activity的LinearLayout上,因此即使AdapterView很友好地将其设置为View.VISIBLE,它也不会显示出来。


扩展 - 我注意到的两个技巧是:1)确保您已经创建并将视图添加到列表视图的父级;2)确保您的适配器的 isEmpty() 方法正确返回 true - Richard Le Mesurier

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接