0

GridView是在我的onCreate这里创建的:

@Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        GridView gridview = (GridView) findViewById(R.id.gridview);
        gridview.setAdapter(new ImageAdapter(this));
...

我的ImageAdapter课程包含对 .png 文件的引用的int[]“图像” 。R.drawable.我的下方有一个 onItemClickListener onCreate,它将根据触摸的位置和时间gridview更新“图像”数组。它看起来像这样,去掉了很多无关的代码:

...
gridview.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v,
                    int position, long id) {

                while (count <= 6) {
...
                    if (count == 2 && verifyEmpty == false
                            && choosePiece == true && chooseEmpty == true) {
                        verifyEmpty = gc.checkEmptyChoice(position);
                        if (verifyEmpty == true) {
                            gc.moveToEmpty(position, gameBoardModel,
                                    (ImageView) v, selectedLocation);
                            count++;
                            // UPDATE THE GRIDVIEW SOMEHOW HERE.
                        }
                        break;
                    }
...

我想gridviewcount++嵌套的if. 它上面的方法gc.moveToEmpty(...)将对images数组进行更改,我希望这些更改反映在gridview. 我曾尝试使用notifyDataSetChanged()invalidateViews但无法使它们中的任何一个在我的onItemClickListener.

-------解决方案----------------来自下面的答案------------- ----

必须为 ImageAdapter 添加名称:

@Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final ImageAdapter iA = new ImageAdapter(this);

        GridView gridview = (GridView) findViewById(R.id.gridview);
        gridview.setAdapter(iA);
...

需要是最终的,所以onClick...可以使用它。然后我可以像这样引用它:

                    if (verifyEmpty == true) {
                        gc.moveToEmpty(position, gameBoardModel,
                                (ImageView) v, selectedLocation);
                        count++;
                        // UPDATE THE GRIDVIEW SOMEHOW HERE.
                        // LIKE THIS!
                        iA.notifyDataSetChanged();
                    }
4

1 回答 1

2

保存对您的引用ImageAdapter,然后调用notifyDataSetChanged

imageAdapter.notifyDataSetChanged()

它通知适配器底层数据已更改并且应该刷新。

于 2013-04-28T04:45:42.643 回答