Android getItem int GridView

时间:2015-05-18 14:32:23

标签: android gridview

我有一个由颜色数组填充的自定义GridView。现在,当我点击该项目时,我想获得单元格的颜色并传递它。我有这个代码,但当我点击该项目时,得到结果(零)

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);
        mAdapter = new ColorPickerAdapter(this);
        grColori.setAdapter(mAdapter);
        grColori.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                int prova = (int) grColori.getItemIdAtPosition(position);
                System.out.println(prova);//here I get 0

                Intent intent = new Intent();
                intent.putExtra("colore", prova);
                setResult(RESULT_OK, intent);

             finish();
        }
    });
}

适配器

public class ColorPickerAdapter extends BaseAdapter {
    private Context context;

    private List<Integer> colorList = new ArrayList<Integer>();

    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);


        } 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;
    }
}

1 个答案:

答案 0 :(得分:0)

而不是从gridview中获取它,而是在适配器中编写一个返回颜色数组颜色的公共方法。这样的事情应该可以解决问题。

在适配器中放入此方法。

public Integer getSelectedColor(int position) {
    return colorList.get(position);
}

然后替换

int prova = (int) grColori.getItemIdAtPosition(position);

int prova = (int) mAdapter.getSelectedColor(position);