2013-05-08 70 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); 
相關問題