2012-04-14 25 views
3

我的問題是如果有可能在主ActivityonCreate()方法setContentView()之前編寫代碼。在下面的代碼中,我想在setContentView()之前調用setVariables(),但這會導致我的應用程序崩潰。如果我在setContentView()之後撥打setVariables(),它可以正常工作。爲什麼是這樣?setContentView故障之前的代碼

package com.oxinos.android.moc; 


import android.app.Activity; 
import android.content.Intent; 
import android.content.SharedPreferences; 
import android.content.res.Resources; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.CheckBox; 


public class mocActivity extends Activity { 
    /** Called when the activity is first created. */ 

    public static String prefsFile = "mocPrefs"; 
    SharedPreferences mocPrefs; 
    public Resources res; 
    public CheckBox cafesCB, barsRestCB, clothingCB, groceriesCB, miscCB; 

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

     mocPrefs = getSharedPreferences(prefsFile,0); 
    } 

    private void setVariables(){ 
     res = getResources(); 
     cafesCB = (CheckBox) findViewById(R.id.cafesCheckBox); 
     barsRestCB = (CheckBox) findViewById(R.id.barsRestCheckBox); 
     clothingCB = (CheckBox) findViewById(R.id.clothingCheckBox); 
     groceriesCB = (CheckBox) findViewById(R.id.groceriesCheckBox); 
     miscCB = (CheckBox) findViewById(R.id.miscCheckBox); 

    } 
    public void submitHandler(View view){ 
     switch (view.getId()) { 
     case R.id.submitButton: 
      boolean cafes = cafesCB.isChecked(); 
      boolean barsRest = barsRestCB.isChecked(); 
      boolean clothing = clothingCB.isChecked(); 
      boolean groceries = groceriesCB.isChecked(); 
      boolean misc = miscCB.isChecked(); 

      SharedPreferences.Editor editor = mocPrefs.edit(); 

      editor.putBoolean(res.getString(R.string.cafesBool), cafes); 
      editor.putBoolean(res.getString(R.string.barsRestBool), barsRest); 
      editor.putBoolean(res.getString(R.string.clothingBool), clothing); 
      editor.putBoolean(res.getString(R.string.groceriesBool), groceries);  
      editor.putBoolean(res.getString(R.string.miscBool), misc); 
      editor.commit(); 
      startActivity(new Intent(this, mocActivity2.class)); 
      break; 
     } 

    } 
} 
+1

儘管這個問題已經得到了充分的回答,只是爲了解釋'setContentView(...)'執行了一種叫'佈局通貨膨脹'的事情。這意味着它會解析相關文件中的XML(在您的案例中爲main.xml),並創建其中所有UI元素的實例。然後它將該觀點附加到該活動。當你調用'findViewById(...)'時,它不會直接引用main.xml,而是引用附加到Activity的內容視圖,換句話說就是'setContentView(...)'誇大的內容視圖。 – Squonk 2012-04-14 12:13:46

回答

9

您可以setContentView()方法之前,只要它不是指(部分)的View,它並沒有被設定執行你想任何代碼。

由於您的setVariables()方法引用的內容爲View,因此無法執行。

1

setContentView()方法將您的XML文件的內容設置爲View,由Activity顯示。

在您指定要顯示的任何View之前,您打電話給setVariables()

這就是錯誤引發的原因。編譯器不知道View所屬的位置。如果你想使用ResourceView,你必須先設置它。

+0

謝謝你們! ...你說什麼是有道理的:) – user1333215 2012-04-14 15:49:40