setContentView之前的代码有问题

use*_*215 3 java android android-view android-activity

我的问题是,如果有可能前编写代码setContentView()onCreate()主要方法Activity.在下面的代码中我想调用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;
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

Pau*_*Jan 9

您可以在方法之前执行任何您想要的代码setContentView(),只要它不引用(View尚未设置)的(部分).

由于您的setVariables()方法引用了其中的内容View,因此无法执行.