2011-12-24 140 views
1

我有這個簡單的代碼,但我無法找到爲什麼它崩潰了應用程序的生活。checkBox.setOnCheckedChangeListener調用崩潰應用程序?

package com.leonnears.android.andAnother; 

import android.app.Activity; 
import android.os.Bundle; 
import android.widget.CheckBox; 
import android.widget.CompoundButton; 

public class AndAnotherActivity extends Activity 
{ 
    CheckBox dahBox; 
    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     dahBox = (CheckBox)findViewById(R.id.someCheck); 
     setContentView(R.layout.main); 
     dahBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() 
     { 
      @Override 
      public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) 
      { 
       if(isChecked) 
       { 
        dahBox.setText("This checkbox is: checked"); 
       }else 
       { 
        dahBox.setText("This checkbox is: unchecked"); 
       } 
      } 
     }); 
    } 
} 

我做了測試和代碼的註釋部分NAD它看起來像調用dahBox.setOnCheckedChangeListener()崩潰我的程序。有一次,我結束了這樣做:

dahBox.setOnCheckedChangeListener(null); 

要查看是否由於某種原因崩潰可能在那裏,它看起來像是。

有人可以幫助我嗎?我會高度讚賞它。

回答

2
dahBox = (CheckBox)findViewById(R.id.someCheck); 
     setContentView(R.layout.main); 

重新排列聲明

setContentView(R.layout.main); 
    dahBox = (CheckBox)findViewById(R.id.someCheck); 

,你必須先設置視圖,然後利用其資源

+0

是的,我剛剛發現這一點,在回答我的問題!哈哈,我覺得很愚蠢。非常感謝您的回覆,我會將您的標記標記爲已選中,而不是發佈自己的帖子。 – 2011-12-24 04:56:43

+0

它不是一個問題 – 2011-12-24 05:05:25