gpt4 book ai didi

java - setContentView 之前的代码麻烦

转载 作者:太空宇宙 更新时间:2023-11-03 11:52:10 25 4
gpt4 key购买 nike

我的问题是是否可以在 ActivityonCreate() 方法中的 setContentView() 之前编写代码。在下面的代码中,我想在 setContentView() 之前调用 setVariables(),但这会导致我的应用程序崩溃。如果我在 setContentView() 之后调用 setVariables(),它工作正常。为什么是这样?

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;
}

}
}

最佳答案

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

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

关于java - setContentView 之前的代码麻烦,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10153376/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com