android - 在运行时将项目添加到 gridview 而不是替换以前的项目

标签 android gridview imageview android-adapter

我按照本教程获得了一个使用自定义适配器显示图像的 GridView : http://www.mkyong.com/android/android-gridview-example/

我已经调整了代码以在将 nfc 卡出示给手机时显示图像,但是如果我多次出示该卡,gridview 中的图像将被替换。我想要这样当手机再次读取 nfc 卡时,它会将图像添加到 gridview,而不是仅仅替换它们。

我怎样才能做到这一点?

                //If the NFC card contains the word "pic"           
            if(thePayloadText.equals("pic")){

                gridView = (GridView) findViewById(R.id.gridView1);

                gridView.setAdapter(new ImageAdapter(this, MOBILE_OS));
        }

            //If the NFC card contains the word "test"
            if(thePayloadText.equals("test")){

                gridView = (GridView) findViewById(R.id.gridView1);
                gridView.setAdapter(new ImageAdapter(this, PHOTOS));

            }

最佳答案

问题是 setAdapter 会清除所有之前的项目。所以你需要在添加新项目时避免使用setAdapter

相反,您需要将新项目添加到现有适配器中。

如果您的自定义适配器是ArrayAdapter,您可以像这样简单地添加

imageAdapter.add(yourObject); // imageAdapter is the instance you created first time when you setAdapter.

add() 方法调用 notifyDataSetChanged 通知 `GridView' 刷新 UI。

如果您的自定义适配器是 BaseAdapter,则在 Custom Adapter 类 中有一个 add() 方法并调用它来添加新项。

public void add(String[] newImages){
    // add the items to the previous array
    this.mobileValues.addAll(Arrays.asList(newItems));
    // notify the data changed
    notifyDataSetChanged();
}

希望对你有帮助。

关于android - 在运行时将项目添加到 gridview 而不是替换以前的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23325605/

相关文章:

c# - 添加指向 gridview 中所有单元格的链接

android - 需要帮助阅读 Android Stacktrace for Mvvmcross fragment crash

android - Android 上的印地语马拉地语字体

android - 使屏幕兼容包含 Canvas

c# - GridView 从抛出异常背后的代码更新

asp.net - 需要 gridview 中单选按钮的帮助

android - 如何修复 ImageView 背景和src?

java - Android Java Bitmap.getByteCount() 显示的大小比实际大小大

iOS:图片幻灯片放映

java - 从短信正文中提取帐号和余额哪种方式更好?