Android 为什么';t“;setContentView”;在if语句中工作?
代码在onCreate中!当Android 为什么';t“;setContentView”;在if语句中工作?,android,Android,代码在onCreate中!当setContentView(R.layout.manual)时在之外。但是我移动了setContentView(R.layout.manual)进入 如下: if (settings.getBoolean("my_first_time", true)) { setContentView(R.layout.manual); // can not work } 但是Log.d(“注释1”,“第一次”)始终有效 @Override publ
setContentView(R.layout.manual)时如果
有效,则code>在之外。但是我移动了setContentView(R.layout.manual)如果
无法工作,则编码>进入
如下:
if (settings.getBoolean("my_first_time", true)) {
setContentView(R.layout.manual); // can not work
}
但是Log.d(“注释1”,“第一次”)代码>始终有效
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final String PREFS_NAME = "MyPrefsFile";
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
if (settings.getBoolean("my_first_time", true)) {
//the app is being launched for first time, do something
Log.d("Comments1", "First time");//this can be showed on logCat!
setContentView(R.layout.manual);// this can not work
// record the fact that the app has been started at least once
settings.edit().putBoolean("my_first_time", false).commit();
}
}
你的情况没有得到满足,因为
settings.getBoolean("my_first_time", true)
这不是真的。
因此你
setContentView(R.layout.manual)
未在“if”块内调用。如果设置if-else循环,则需要知道正在执行的操作,因为无论结果如何,setContentView()
必须提供有效的布局id。如果在设置布局之前需要检查条件,则只需检查id:
int layoutId=0;
if(condition) {
layoutId = R.layout.manual;
} else {
layoutId = R.layout.other;
}
setContentView(layoutId);
public void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.manual);这样使用,因为if条件可能为false。发布完整的onCreate代码。