2012-04-14 22 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