有没有一种模块化的方法来初始化ImageView数组

时间:2019-12-01 15:48:40

标签: android arrays android-imageview

我已经开始了有关android studio和android开发的课程, 我们的首要任务是使用线性布局创建一个简单的躲避游戏,该线性布局包含“要躲避的对象”的图像视图。 任务的一部分是使代码尽可能模块化,这就是我遇到的问题,

是否有更模块化的方式来初始化ImageView的数组\矩阵? 这就是我发现的工作方式:


public class GameActivity extends AppCompatActivity {
    private int imgId[] = {
            R.id.rocket_0_0, R.id.rocket_0_1, R.id.rocket_0_2, R.id.rocket_1_0, R.id.rocket_1_1, R.id.rocket_1_2, R.id.rocket_2_0, R.id.rocket_2_1,
            R.id.rocket_2_2, R.id.rocket_3_0, R.id.rocket_3_1, R.id.rocket_3_2, R.id.rocket_4_0, R.id.rocket_4_1, R.id.rocket_4_2, R.id.rocket_5_0, R.id.rocket_5_1,
            R.id.rocket_5_2, R.id.rocket_6_0, R.id.rocket_6_1, R.id.rocket_6_2};
    private ImageView [][] imgMatrix;
    private int rows = R.integer.row;
    private int cols = R.integer.col;
    private MyLogic myLogic = new MyLogic();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_game);
        imgMatrix = new ImageView[][]
                        {{findViewById(imgId[0]), findViewById(imgId[1]),findViewById(imgId[2])},{findViewById(imgId[3]),findViewById(imgId[4]),findViewById(imgId[5])},
                        {findViewById(imgId[6]),findViewById(imgId[7]),findViewById(imgId[8])},{findViewById(imgId[9]),findViewById(imgId[10]),findViewById(imgId[11])},
                        {findViewById(imgId[12]),findViewById(imgId[13]),findViewById(imgId[14])},{findViewById(imgId[15]),findViewById(imgId[16]),findViewById(imgId[17])},
                        {findViewById(imgId[18]),findViewById(imgId[19]),findViewById(imgId[20])}};

    }
}

这就是我想要的工作:),但是它崩溃了:(

public class GameActivity extends AppCompatActivity {
    private int imgId[] = {
            R.id.rocket_0_0, R.id.rocket_0_1, R.id.rocket_0_2, R.id.rocket_1_0, R.id.rocket_1_1, R.id.rocket_1_2, R.id.rocket_2_0, R.id.rocket_2_1,
            R.id.rocket_2_2, R.id.rocket_3_0, R.id.rocket_3_1, R.id.rocket_3_2, R.id.rocket_4_0, R.id.rocket_4_1, R.id.rocket_4_2, R.id.rocket_5_0, R.id.rocket_5_1,
            R.id.rocket_5_2, R.id.rocket_6_0, R.id.rocket_6_1, R.id.rocket_6_2};
    private ImageView [][] imgMatrix;
    private int rows = R.integer.row;
    private int cols = R.integer.col;
    private MyLogic myLogic = new MyLogic();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_game);

        imgMatrix = new ImageView[rows][cols];

        for(int i = 0; i < rows; i++){
             for(int j = 0; j < cols; j++){
                   imgMatrix[i][j] = findViewById(imgId[i*cols+j]);
             }
        }

如果可以的话,感谢您的阅读和帮助:

0 个答案:

没有答案