2014-12-20 29 views
0

我使用共享首選項來保存用戶頁碼。所以當用戶重新加載應用程序時,他們可以繼續閱讀他們離開的地方。他們的方式,我做了它的工作,但感覺凌亂,因爲這將結束像400如果和其他條件。有一個更好的方法嗎。許多thxAndroid對很多if和else條件

@Override 
public void onClick(View v) { 
    // TODO Auto-generated method stub 
     if (firstcheck.getText().toString().equals("")){ 
     SavePrefs("FIRST_CHECK", firstcheck.getText().toString()); 
     Intent myIntent = new Intent(SplashActivity.this, ConfigurationActivity.class); 
     startActivity(myIntent); 
     }else{ 
     if (firstcheck.getText().toString().equals("0")){ 
     Intent myIntent = new Intent(SplashActivity.this, BackgroundActivity.class); 
     startActivity(myIntent); 
     }else{ 
     if (firstcheck.getText().toString().equals("1")){ 
     Intent myIntent = new Intent(SplashActivity.this, Page1Activity.class); 
     startActivity(myIntent); 
+0

爲什麼在這裏要保存字符串值,而不是整數? –

+0

我是java和android的新手,所以還有很多東西需要學習。猜它只是我遵循的教程,它似乎適用於我想要嘗試和做的事情。將考慮將其改爲一個整數,因爲這是有道理的。 thx –

回答

0

我的首選處理方法是使用枚舉。

public enum IfReplacement { 
CASE_1("0") { 

    public void handle(...) { 
     //code for case "0" here. 
    } 

}, 
CASE_2("1") { 

    public void handle(...) { 
     //code for case "1" here 
    } 

}; 

    private static final Map<String, IfReplacement> VALUES; 
    static { 
     Map<String, IfReplacement> map = new HashMap<String, IfReplacement>(); 
     for(IfReplacement rep : IfReplacement.values()) { 
      map.put(rep.key, rep); 
     } 
     VALUES = Collections.unmodifiableMap(map); 
    } 

    private final String key; 

    private IfReplacement(String key) { 
     this.key = key; 
    } 

    public abstract void handle(... your parameters here ...) 

    public static void handle(String key, ... your parameters here ...) { 
     IfReplacement handler = VALUES.get(key); 
     if(handler != null) { 
      handler.handle(...); 
     } else { 
      //error or default logic here 
     } 
    } 

} 

編輯:

這個代碼寫在瀏覽器中,因此它可能包含一些錯別字。但是這個概念應該清楚。