尝试使用循环查找视图时应用程序崩溃

时间:2014-01-26 19:12:25

标签: android

我正在尝试使用“键盘”创建一个小应用程序(14个按钮),我无法使用循环工作来获取“findViewById”。每当我参加这项活动时,它都会立即崩溃,甚至没有向我显示任何内容。不知道我在这里做错了什么。 我可以帮忙吗?

package com.vessilate.findtheword;

import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.ImageView;

public class Level extends Activity {
    ImageView ivPic1, ivPic2, ivPic3, ivPic4;
    int[] buttons = new int[] { R.id.bKey1, R.id.bKey2, R.id.bKey3, R.id.bKey4,
        R.id.bKey5, R.id.bKey6, R.id.bKey7, R.id.bKey8, R.id.bKey9,
        R.id.bKey10, R.id.bKey11, R.id.bKey12, R.id.bKey13, R.id.bKey14, };
    Button[] bKeys;

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

        String levelExtra = getIntent().getStringExtra("level");
        int level = Integer.parseInt(levelExtra);

        // initialize views
        ivPic1 = (ImageView) findViewById(R.id.ivPic1);
        ivPic2 = (ImageView) findViewById(R.id.ivPic2);
        ivPic3 = (ImageView) findViewById(R.id.ivPic3);
        ivPic4 = (ImageView) findViewById(R.id.ivPic4);

        // setup keyboard
        for (int i = 0; i < bKeys.length; i++) {
            bKeys[i] = (Button) findViewById(buttons[i]);
        }

        switch (level) {
        case 1:
            // shoes
            ivPic1.setBackgroundResource(R.drawable.level1_1);
            ivPic2.setBackgroundResource(R.drawable.level1_2);
            ivPic3.setBackgroundResource(R.drawable.level1_3);
            ivPic4.setBackgroundResource(R.drawable.level1_4);
            break;

        case 2:

            break;

        case 3:

            break;

        case 4:

            break;
        }
    }

}

谢谢。

1 个答案:

答案 0 :(得分:2)

您永远不会初始化bKeys。在onCreate()的开头添加:

bKeys = new Button[buttons.length];