代码之家  ›  专栏  ›  技术社区  ›  akhilc

更改图像的二维数组OnClick

  •  0
  • akhilc  · 技术社区  · 8 年前

    我是Android开发(和Java)的初学者。我有很多 ImageView 在布局中(二维图像阵列)。我想实现的是,每次我点击 图片框 ,它应该根据当前图像显示的某些逻辑设置阵列中的图像(例如,每次单击后阵列中的下一个图像)。我已经在谷歌上搜索并成功地做到了这一点,但它看起来相当长。

    public class GameActivity extends AppCompatActivity {
        private int [] inputTiles = {R.drawable.one, R.drawable.two, ...// more images};
        Random r = new Random();
        int matSize = 5;
        int[][] indexMat = new int[matSize][matSize];
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_game);
    
            for (int i=0; i<matSize; i++) {
                for (int j=0; j<matSize; j++) {
                    indexMat[i][j] = r.nextInt(10);
                }
            }
    
            final ImageView tile00 = findViewById(R.id.tile00);
            tile00.setImageResource(inputTiles[indexMat[0][0]]);
            tile00.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                indexMat[0][0] = (indexMat[0][0]+1)%5;
                tile00.setImageResource(inputTiles[indexMat[0][0]]);
                }
            });
    
            final ImageView tile01 = findViewById(R.id.tile01);
            tile01.setImageResource(inputTiles[indexMat[0][1]]);
            tile01.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    indexMat[0][1] = (indexMat[0][1]+1)%5;
                    tile01.setImageResource(inputTiles[indexMat[0][1]]);
                }
            });
    
            ...// a lot more ImageViews
    
        }
    }
    

    假设我正在显示5x5网格的图像。我有一个数组中的可用图像 inputTiles 和5x5阵列 indexMat 将当前图像的索引存储在某个位置 i , j . 然后,对于每个 图片框 我正在侦听单击并从阵列中选择另一个要显示的图像。这工作得很好,但在这个特定的示例中,我必须写“clicklisten and action”块25次。如果有一种循环的方法,这样我就可以 n x n 网格

    我在google上搜索了一下后,通过保持 图片框 在5x5数组中循环,但循环变量似乎不在 setOnClickListener() 作用上面说我需要 j final 但它变成常数,所以不起作用。下面的代码是我尝试过的,但它不能以这种方式工作。

    final ImageView[][] tiles = {{findViewById(R.id.tile00), findViewById(R.id.tile01), findViewById(R.id.tile02),...},
            {findViewById(R.id.tile10), ...,}};
    
    for (int i=0; i<3;i++){
        for (int j=0; j<3; j++){
            tiles[i][j].setImageResource(inputTiles[indexMat[i][j]]);
            tiles[i][j].setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    indexMat[i][j] = //doesn't work
                }
            });
        }
    }
    

    有什么想法吗?

    1 回复  |  直到 8 年前
        1
  •  1
  •   Reaz Murshed vir us    8 年前

    最简单的方法是 RecyclerView 用一个 GridLayoutManager . 这里有一个 nice example 关于如何在 回收视图 .

    在中设置这些图像后 回收视图 ,您可以轻松管理 onBindViewHolder 函数,基于您单击的位置。