2013-05-08 69 views
-2

代码在onCreate! setContentView(R.layout.manual);if之外时有效。但我搬到if不能工作setContentView(R.layout.manual);为什么“setContentView”不能在if语句中工作?

的followign:

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

} 
+0

公共无效的onCreate(捆绑savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.manual);像这样使用,因为如果条件可能是错误的。 – 2013-05-08 05:22:49

+0

发布完整的onCreate代码。 – 2013-05-08 05:25:38

回答

2

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

settings.getBoolean("my_first_time", true) 

不返回true。 因此您

的setContentView(R.layout.manual)

不叫“如果”块中。

2

如果你设置了一个if-else循环,你需要知道你在做什么,因为无论结果setContentView()必须提供一个有效的布局ID。如果你有一个条件设置布局前的检查,你可以检查ID:

int layoutId=0; 
if(condition) { 
    layoutId = R.layout.manual; 
} else { 
    layoutId = R.layout.other; 
} 
setContentView(layoutId); 
相关问题