我的 GridView 应该包含 7 个元素,结果我只看到一个(数据 ArrayList 的最后一个)。
LevelsAdapter 扩展 BaseAdapter:
private TextView star;
private TextView label;
private TextView percent;
Typeface font;
private ArrayList<Level> levels;
LayoutInflater inflater;
public LevelsAdapter(Activity context, ArrayList<Level> levels) {
super();
this.levels = levels;
font = Typeface.createFromAsset(context.getAssets(), "fonts/Boogaloo-Regular.ttf");
inflater = context.getLayoutInflater();
}
@Override
public int getCount() {
return levels.size();
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
Log.d("LevelsAdapter2", "position is "+position+", convertView is "+convertView);
View vi=convertView;
if(convertView==null) vi = inflater.inflate(R.layout.item_level, null);
star = (TextView) vi.findViewById(R.id.star);
percent = (TextView) vi.findViewById(R.id.percent);
label = (TextView) vi.findViewById(R.id.level_number);
star.setTypeface(font);
label.setTypeface(font);
percent.setTypeface(font);
Level lvl = levels.get(position);
percent.setText(lvl.getPercent() + "%");
label.setText("#"+lvl.getId());
return vi;
}
正如您所看到的,每次调用 getView 方法时,我们都会记录其当前参数。然后 LogCat 返回奇怪的行:
LevelsAdapter2(15508): position is 0, convertView is null
LevelsAdapter2(15508): position is 0, convertView is android.widget.RelativeLayout@41a9d120
LevelsAdapter2(15508): position is 0, convertView is android.widget.RelativeLayout@41a9d120
LevelsAdapter2(15508): position is 0, convertView is android.widget.RelativeLayout@41a9d120
LevelsAdapter2(15508): position is 0, convertView is android.widget.RelativeLayout@41a9d120
LevelsAdapter2(15508): position is 0, convertView is null
LevelsAdapter2(15508): position is 0, convertView is android.widget.RelativeLayout@41ad9770
编辑:错误是在创建 ArrayList 并错误填充时。帮助替换了这个:
private void constructLevels() {
Level lvl = new Level();
for (int i=0; i<lvls.length; i++) {
int id = i + 1;
lvl.setId(id);
lvl.setWord(lvls[i]);
}
addLevel(lvl);
}
对此:
private void constructLevels() {
Level lvl;
for (int i=0; i<lvls.length; i++) {
lvl = new Level();
int id = i + 1;
lvl.setId(id);
lvl.setWord(lvls[i]);
addLevel(i, lvl);
}
}