Android:有没有办法重置自动生成的 id 的计数器?

问题描述

一个 Activity 中,我有一个 GridLayout,它包含三个不同的磁贴,表示为 ImageViews。他们得到一个自动 ID:

private void createLayout() {
  int[] board = create(); // Create and show the internal representation. 

  // Prepare the GridLayout by clearing and setting limits. 
  GridLayout grid = findViewById(R.id.board);
  grid.removeAllViews();
  grid.setColumnCount(maxCols);
  grid.setRowCount(maxRows);

  // Fill the GridLayout dynamically dependent on the board.
  for (int col : board) {
    int i = 0;

   // Fill with clickable tiles as long as there are clickable tiles expected.
    while (i < col) {
      grid.addView(createTile(true));
      i++;
    }

    // Fill empty tiles when there are no clickable tiles expected.
    while (i < maxCols) {
      grid.addView(createTile(null));
      i++;
    }
  }
}
... 
private ImageView createTile(Boolean isClickable) {
ImageView tile = new ImageView(this);
tile.setId(View.generateViewId()); // Generate an id [1,n] for n dynamic elements.
...
}

虽然它不会增加问题,但您可能仍然想知道为什么我使用 Booleannull:有可点击的图块({{1} })、之前点击的图块isClickable = true)和空图块((isClickable = false)。但是 id 非常重要,因为您可以通过这种方式轻松确定列和行,我稍后在逻辑中需要该信息:

isClickable = null

但是,当我关闭 Activity 并从主 Activity 内部重新启动它时,tile 的 id 计数器不会重置并继续递增,最终导致 private int getCol(int id) { int col = id % maxCols; return (col == 0) ? maxCols : col; } private int getRow(int id) { boolean isMultiple = (id % maxCols) == 0; return isMultiple ? ((int) (double) id / maxCols) - 1 : (int) (double) id / maxCols; ,因为网格表示为 { {1}} 在逻辑中。那么,有没有办法重置这个计数器?

到目前为止我尝试过的

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)