我将它用于网格视图,显示的对象计数是正确的,它在日志中的返回是正确的,例如6个对象显示,其余的重复它们
1,2,3,4,5,6,1,2,3,4,5,6,.....
我的代码
public class CustomAdapter extends ArrayAdapter<ItemObject> {
private static float textViewWidth;
public CustomAdapter(ArrayList<ItemObject> array, float textViewWidth) {
super(G.context, R.layout.sample_album_item, array);
CustomAdapter.textViewWidth = textViewWidth;
}
private static class ViewHolder {
ImageView imgScreenShot;
TextView txtAlbumName;
TextView txtAlbumAuthor;
public ViewHolder(View view) {
imgScreenShot = (ImageView) view.findViewById(R.id.screen_shot);
txtAlbumName = (TextView) view.findViewById(R.id.album_name);
txtAlbumAuthor = (TextView) view.findViewById(R.id.album_author);
}
public void fill(final ArrayAdapter<ItemObject> adapter, final ItemObject item, final int position) {
imgScreenShot.setImageResource(item.getScreenShot());
String albumName = item.getAlbumName();
String albumAuthor = item.getAlbumAuthor();
float musicNameWidthSizeViaParent = widthSizeViaParent(txtAlbumName, albumName);
float musicAuthorWidthSizeViaParent = widthSizeViaParent(txtAlbumAuthor, albumAuthor);
if (musicNameWidthSizeViaParent < 0) {
for (int i = 1; i < albumName.length() - 1; i++) {
if (widthSizeViaParent(txtAlbumName, albumName.substring(0, i).trim() + "...") < 0) {
albumName = albumName.substring(0, i - 1).trim() + "...";
break;
}
}
}
if (musicAuthorWidthSizeViaParent < 0) {
for (int i = 1; i < albumAuthor.length() - 1; i++) {
if (widthSizeViaParent(txtAlbumName, albumAuthor.substring(0, i).trim() + "...") < 0) {
albumAuthor = albumAuthor.substring(0, i - 1).trim() + "...";
break;
}
}
}
txtAlbumName.setText(albumName);
txtAlbumAuthor.setText(albumAuthor);
}
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
ItemObject item = getItem(position);
if (convertView == null) {
convertView = G.inflater.inflate(R.layout.sample_album_item, parent, false);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.fill(this, item, position);
return convertView;
}
private static float widthSizeViaParent(TextView text, String newText) {
float textWidth = text.getPaint().measureText(newText);
return textViewWidth - (textWidth * G.displayMetrics.density);
}
}
如果getView方法没有这个(convertView == null)条件,一切都正确但滚动很慢
答案 0 :(得分:0)
我的猜测是这段代码会让它运行缓慢:
.text()
每个项目都会运行两个循环。您可能希望在模型中使用该逻辑。因此,在渲染项目时,已经设置了albumName和albumAuthor。