我有一个由颜色数组填充的自定义GridView。 现在,当我点击该项目时,我想获得单元格的颜色。 我有这个代码,但是当我单击该项时,获取java.lang.NullPointerException。
public class Colori_picker extends Activity {
private GridView grColori;
private ColorPickerAdapter mAdapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.color_picker);
grColori= (GridView) findViewById(R.id.gridViewColors);
grColori.setAdapter(new ColorPickerAdapter(this));
grColori.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Object color = mAdapter.getItem(position);
finish();
}
});
}
适配器
public class ColorPickerAdapter extends BaseAdapter {
private Context context;
// list which holds the colors to be displayed
private List<Integer> colorList = new ArrayList<Integer>();
// width of grid column
int colorGridColumnWidth;
public ColorPickerAdapter(Context context) {
this.context = context;
String colors[][] = {
{ "83334C", "B65775", "E07798", "F7A7C0", "FBC8D9", "FCDEE8" },
{ "000000", "434343", "666666", "999999", "CCCCCC", "EFEFEF" } };
colorList = new ArrayList<Integer>();
// add the color array to the list
for (int i = 0; i < colors.length; i++) {
for (int j = 0; j < colors[i].length; j++) {
colorList.add(Color.parseColor("#" + colors[i][j]));
}
}
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(context);
// set the width of each color square
imageView.setLayoutParams(new GridView.LayoutParams(colorGridColumnWidth, colorGridColumnWidth));
} else {
imageView = (ImageView) convertView;
}
imageView.setBackgroundColor(colorList.get(position));
imageView.setId(position);
return imageView;
}
public int getCount() {
return colorList.size();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
}
答案 0 :(得分:1)
发生的事情是您声明了实例变量mAdapter但从未实例化它。您需要做的就是改变这个
grColori.setAdapter(new ColorPickerAdapter(this));
到此
mAdapter = new ColorPickerAdapter(this);
grColori.setAdapter(mAdapter);