我为ListView
实现了ArrayAdapter,其中每行包含TextView
和ImageButton
。
ImageButton 的背景图片取决于某些条件,有两种选择:
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.item_with_button, null);
File f = new File(PATH_TO_FILE);
if(f.exists()){
imbutton =(ImageButton)vi.findViewById(R.id.btn_image);
imbutton.setBackgroundResource(R.drawable.done);
}else
{
imbutton =(ImageButton)vi.findViewById(R.id.btn_image);
imbutton.setBackgroundResource(R.drawable.download);
imbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String url = URL;
new DownloadFileAsync(pos).execute(url);
}
});
}
...
return vi;
}
如果文件存在,那么我在 ImageButton 上设置“完成”图像。如果文件不存在,我设置“下载”图像。
用户单击ImageButton
后,文件将下载,我需要更改相应的图像。
问题是,仅当用户向下滚动 ListView
直到此 ImageButton
从屏幕上消失然后向后滚动时,才会调用 getView
。之后该按钮将出现并带有新的背景图像。
但是,我目前无法使显示新图像的按钮无效。
我使用此类进行异步下载:http://www.java-samples.com/showtutorial.php?tutorialid=1521
我尝试在函数中创建类似 currentbutton.invalidate()
的内容
@Override
protected void onPostExecute(String unused) {
activity.dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
但没有成功。
如何使 ImageButton
无效以显示新的背景图像?
最佳答案
您可以调用notifyDataSetChanged在 onClick 监听器中强制刷新列表。 不过我还没有尝试过,所以我不确定如果不对适配器进行任何显式更改(即添加、删除或更新其上的项目),它是否可以工作。
我稍后会检查它,如果它不能开箱即用,我会写下任何进一步的建议。
编辑:实际上你需要调用notifyDataSetChanged在您正在使用的 AsyncTask 的 onPostExecute 方法中,而不是在 onClick 监听器中。
关于Android:动态更改ImageButton的背景并显示它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9886547/