我按照本教程获得了一个使用自定义适配器显示图像的 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/