我有一个适配器,可以在 gradview 中创建 16 个按钮,因为正在创建按钮,然后我给出一个标签并将其添加到数组中,由于某种原因,当我打印日志时它显示了 17 个元素......任何想法为什么它当我创建 16 个按钮时包含 17 个元素...
public class ButtonAdapter extends BaseAdapter {
private Context mContext;
ArrayList<String> colorsArray = new ArrayList<String>(0);// add button tags
public ButtonAdapter(Context c) {
mContext = c;
}
public int getCount() {
int a = 16;// HOW MANY TILES WILL THE ADAPTER DISPLAY AND CREATE IN
// THE GRID VIEW, REFRENCED IN THE onCreate METHOD BELOW
return a;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
final Button button;
if (convertView == null) {
int r = 1 + (int) (Math.random() * 5);
button = new Button(mContext);
button.setLayoutParams(new GridView.LayoutParams(100, 100));
button.setText("" + r);// set text to random number
// give each button a new reference number
int r4 = 1 + (int) (Math.random() * 5);
int r3 = 1 + (int) (Math.random() * 4);
int r2 = 1 + (int) (Math.random() * 3);
int r1 = 1 + (int) (Math.random() * 2);
// setup attributes for each button
if (r == 5) {
button.setBackgroundColor(yellow);
button.setText("" + r4);// set text to new random number
colorsArray.add("yellow");
button.setTag("yellow");
} else if (r == 4) {
button.setBackgroundColor(green);
button.setText("" + r3);
colorsArray.add("green");
button.setTag("green");
} else if (r == 3) {
button.setBackgroundColor(red);
button.setText("" + r2);
colorsArray.add("red");
button.setTag("red");
} else if (r == 2) {
button.setBackgroundColor(blue);
button.setText("" + r1);
colorsArray.add("blue");
button.setTag("blue");
} else if (r == 1) {
button.setBackgroundColor(purple);
colorsArray.add("purple");
button.setTag("purple");
} else {
button.setBackgroundColor(white);
button.setText("0");
}
Log.d(TAG, colorsArray.toString());
} else {
button = (Button) convertView;
}
return button;