猿问

更新 GridView

当我点击一个项目时,我需要更新我的 gridView。我尝试了很多东西,但没有任何效果。我的活动有以下代码:


public class GameActivity extends AppCompatActivity implements IGameView{


public GridGame _gridGame = new GridGame();

public GamePresenter _presenter = new GamePresenter(this, _gridGame);

public ImageAdapter _imageAdapter = new ImageAdapter(this, _gridGame);


@Override

public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.

    getMenuInflater().inflate(R.menu.main, menu);

    return true;

}


@Override

public boolean onOptionsItemSelected(MenuItem item) {

    // Handle action bar item clicks here. The action bar will

    // automatically handle clicks on the Home/Up button, so long

    // as you specify a parent activity in AndroidManifest.xml.

    int id = item.getItemId();


    //noinspection SimplifiableIfStatement

    if (id == R.id.action_help) {

        Intent intent = new Intent(this, HelpActivity.class);

        startActivity(intent);

        return true;

    }


    return super.onOptionsItemSelected(item);

}


@Override

protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_game);


    final Context context = this;


    final GridView gridview = (GridView) findViewById(R.id.gridview);

    gridview.setAdapter(_imageAdapter);


    gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        public void onItemClick(AdapterView<?> parent, View v,

                                int position, long id) {

            _presenter.addPawn(position);

            _imageAdapter.update(position, _presenter.actualPlayer);

            Toast.makeText(context, "" + position,Toast.LENGTH_SHORT).show();

        }

    });

}


当我单击一个正方形(gridview 上的项目)时,我希望视图更新显示其他图像而不是正方形。当我在 ImageAdapter 上调用 update 方法但视图不更新时,更新完成。


泛舟湖上清波郎朗
浏览 163回答 3
3回答

缥缈止盈

首先,您需要修复方法以返回适配器所需的数据,以将项目对象标识为// return the new data from sourcein case of updatepublic Object getItem(int position) {&nbsp; &nbsp; return grid[position];}// don't send 0 alwayspublic long getItemId(int position) {&nbsp; &nbsp; return position;}// invoke notifyDataSetChanged(); when there is a change in data sourcepublic void update(int id, int player){&nbsp; &nbsp; grid[id] = R.drawable.ic_notifications_black_24dp;&nbsp; &nbsp; notifyDataSetChanged();}

吃鸡游戏

您需要通知适配器数据元素已更改。试试这个update()方法:public void update(int id, int player){&nbsp; &nbsp; grid[id] = R.drawable.ic_notifications_black_24dp;&nbsp; &nbsp; notifyDataSetChanged();}

侃侃尔雅

好的,我发现了问题,我在 中设置了网格,getView(int position, View convertView, ViewGroup parent);但它应该在构造函数中设置。问题是每次我点击一个项目时它都会重置网格中的值,所以该值没有改变。
随时随地看视频慕课网APP

相关分类

Java
我要回答