隐藏其他背景的不同情况下的复选框

时间:2015-03-15 22:55:12

标签: android checkbox onclicklistener

我正在创建此活动,使用random从字符串数组中提取问题。在不同的问题中,我给出了与我的活动不同的背景来匹配问题的主题。我所拥有的是一个用于复选框的单击侦听器,用户需要按下所选问题的正确复选框。我想在不同的背景(和问题)中显示不同的复选框,所以我已经在我的布局中实现了所有复选框,包括android:visibility="gone"并尝试checkBox1.setVisibility(View.VISIBLE);我一直在我的行中获得NullPointerException将复选框的可见性设置为可见。有人可以解释一下吗?代码在下面

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

    TextView countsTxt = (TextView) findViewById(R.id.txtCounts);
    questions = getResources().getStringArray(R.array.questions);       
    CheckBox centerBack = (CheckBox) findViewById(R.id.centerBack);
    CheckBox checkBox1 = (CheckBox) findViewById(R.id.checkBox1);
    CheckBox checkBox2 = (CheckBox) findViewById(R.id.checkBox2);
    CheckBox checkBox3 = (CheckBox) findViewById(R.id.checkBox3);
    CheckBox checkBox4 = (CheckBox) findViewById(R.id.checkBox4);
    CheckBox checkBox5 = (CheckBox) findViewById(R.id.checkBox5);
    CheckBox checkBox6 = (CheckBox) findViewById(R.id.checkBox6);

    centerBack.setOnClickListener(this);
    checkBox1.setOnClickListener(this);
    checkBox2.setOnClickListener(this);
    checkBox3.setOnClickListener(this);
    checkBox4.setOnClickListener(this);
    checkBox5.setOnClickListener(this);
    checkBox6.setOnClickListener(this);

    countsTxt.setTextColor(Color.parseColor("#0033CC"));
    countsTxt.setTextSize(24);
    countsTxt.setText("Tries: " + triesLeft); 

}

 @Override
    protected void onResume() {
        super.onResume();

        counts = 0;
        getQuestion();
    }

@SuppressLint("NewApi") private void getQuestion(){
    TextView questionText = (TextView) findViewById(R.id.question);
    questionText.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
    questionText.setTextSize(24);

    RelativeLayout screenGame = (RelativeLayout) findViewById(R.id.screenGame); 

    Random rand = new Random();
    int maxIndex = questions.length;
    int generatedIndex = rand.nextInt(maxIndex);        
    if(questions[generatedIndex].equals("Click on the player with the possition of a Center Back")){
        screenGame.setBackground(getResources().getDrawable(R.drawable.footballfindtheposition));
        checkBox1.setVisibility(View.VISIBLE);
    }
    else if(questions[generatedIndex].equals("Click on the area where Player should serve in order to be valid")){
        screenGame.setBackground(getResources().getDrawable(R.drawable.tenniscourt));
    }
    questionText.setText(questions[generatedIndex]);
}

1 个答案:

答案 0 :(得分:0)

复选框变量定义为oncreate方法......那是错误的。 将代码更改为:

private CheckBox checkBox1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tennis_facts);
checkBox1 = (CheckBox) findViewById(R.id.checkBox1);
}

并且不记得onclick功能。