2012-07-29 53 views
0

我試圖在Android中初始化組件,我搜索了互聯網,發現了這種類型的聲明,但它使我的程序在啓動時強制關閉。我究竟做錯了什麼?聲明Android中的組件崩潰程序

public class MainActivity extends Activity { 

    private EditText edit =(EditText) findViewById(R.id.editText3); // This code makes my program come up totally empty and crash in few seconds after being blank. 


     @Override 
     public void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.activity_main); 
     } 



     @Override 
     public boolean onCreateOptionsMenu(Menu menu) { 
      getMenuInflater().inflate(R.menu.activity_main, menu); 
      return true; 
     } 


    } 

回答

1

在設置佈局之前,您無法獲取對任何小部件的引用。請嘗試以下代碼:

public class MainActivity extends Activity { 

private EditText edit; 


    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     edit =(EditText) findViewById(R.id.editText3); 
    } 

    public void startScan(View view){ 
     //edit.append(seekBar1.getProgress()+"\n"); 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     getMenuInflater().inflate(R.menu.activity_main, menu); 
     return true; 
    } 


} 
+0

Aweseome!謝謝 :) – 2012-07-29 15:03:24