-2

代码在 onCreate!什么时候setContentView(R.layout.manual);在外面if它工作。但是我搬进setContentView(R.layout.manual);if不能工作!

如下图:

if (settings.getBoolean("my_first_time", true)) { 
    setContentView(R.layout.manual); // can not work
}  

Log.d("Comments1", "First time");总是有效

    @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(); 
        }

}
4

2 回答 2

2

你的条件没有得到满足,因为

settings.getBoolean("my_first_time", true)

没有返回真。因此你的

setContentView(R.layout.manual)

不在“if”块内调用。

于 2013-05-08T05:26:19.220 回答
2

如果设置 if-else 循环,您需要知道自己在做什么,因为无论结果如何,都setContentView()必须提供有效的布局 ID。如果在设置布局之前有条件要检查,可以只检查 id:

int layoutId=0;
if(condition) {
    layoutId = R.layout.manual;
} else {
    layoutId = R.layout.other;
}
setContentView(layoutId);
于 2013-05-08T05:35:37.620 回答