【发布时间】:2014-11-19 09:54:31
【问题描述】:
我有一个 GridView,每个单元格下面有一个 ImageView 和一个 TextView。
逻辑运作良好。我参考了我的 GridView,设置了列并设置了适配器。在此期间,我有一个线程将图像及其名称设置为列表。 (一个用于图像的 DrawAble 列表和一个用于标签的字符串列表)。为了满足我的用户,我想在线程将图像和标签添加到列表时更新 GridView。
但更新仅在我提供讨厌的静态变量时才有效。 (我恨他们)。或者,如果我每次发生更新时都将适配器设置为 GridView。 (这也很讨厌,因为您无法在 ist 更新期间滚动 GridView ..)
这是我的自定义适配器:
public CustomAdapter(DialogBox dialogBoxActivity,List<Drawable> imported_scaled_images, List<String> imported_labels, int position) {
this.context = dialogBoxActivity;
this.scaledImage = imported_scaled_images.toArray(new Drawable[imported_scaled_images.size()]);
this.labels = imported_labels.toArray(new String[imported_labels.size()]);
this.used_cells = position;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void updateGrid(List<Drawable> imported_scaled_images, List<String> imported_labels, int position) {
this.scaledImage = imported_scaled_images.toArray(new Drawable[imported_scaled_images.size()]);
this.labels = imported_labels.toArray(new String[imported_labels.size()]);
this.used_cells = position;
this.notifyDataSetChanged();
Log.e("update","true");
}
@Override
public void notifyDataSetChanged() {
// TODO Auto-generated method stub
super.notifyDataSetChanged();
Log.e("notify","true");
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return used_cells;
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class Holder {
ImageView img;
TextView tv;
public Holder(ImageView img, TextView tv) {
this.img = img;
this.tv = tv;
}
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ImageView img;
TextView tv;
TextView tv_abc;
if(convertView == null) {
convertView = inflater.inflate(R.layout.customadapter_view_layout, null);
img = (ImageView) convertView.findViewById(R.id.img);
tv =(TextView) convertView.findViewById(R.id.tv);
//tv_abc = (TextView) convertView.findViewById(R.id.tv_normal_portrait_abc);
convertView.setTag(new Holder(img,tv));
} else {
Holder holder = (Holder) convertView.getTag();
img = holder.img;
tv = holder.tv;
//tv_abc = holder.tv_abc;
}
img.setImageDrawable(scaledImage[position]);
tv.setText(labels[position]);
notifyDataSetChanged();
return convertView;
}
}
在我的 Activity 上,我有 updateGrid,我在 MainThread 上的 TimerTask 中调用它:
private void updateGrid() {
customAdapter.updateGrid(images, labels, position);
}
发生的情况是 GridView 保持为空。也许是因为当我将 baseadapter 设置为 gridview 时 Position 为 0。但这不可能是问题,因为当我更新时它应该识别 getCount() 中的新大小。再一次,逻辑运作良好。添加的图像以及方法 updateGrid 和 notiyDataSetChanged 被称为我想要的。但是 GridView 保持不变,我不喜欢显示这些图像。(完全为空)。
希望可以提供一个好的解决方案。我感谢我在上面发布的代码的每一次帮助和每一次改进。(关于性能或其他)。谢谢!
更新:位置是我的变量,它计算可用的单元格。因为有些单元格是空的(=null)。由于我不知道将填充多少单元格(因为我按字母顺序对图像进行排序(对于每一行 => 一些单元格填充为空)我无法在我的逻辑之前为 BaseAdapters getCount 方法提供一个数字' t完成)
【问题讨论】: