2013-07-20 19 views
2

我是一個新手,我正在編寫一個簡單的Android應用程序,它有幾個活動。在每個活動中,我必須使用進度對話框和自定義佈局Toast。另外我必須在其中的一些中保存和加載首選項。 如何將所有這些方法放在單獨的類中,我不想在每個活動中編寫相同的代碼。它可以是一個靜態類嗎?如何創建一個單獨的類來處理android常見任務,如創建進度對話框?

謝謝。

private void createCustomToast(String msg, String status) { 
    Context context = getApplicationContext(); 
    LayoutInflater inflater = getLayoutInflater(); 
    View toastRoot = inflater 
      .inflate(R.layout.custom_toast_two_lines, null); 
    TextView text = (TextView) toastRoot.findViewById(R.id.toastText); 
    TextView textTriageStatus = (TextView) toastRoot 
      .findViewById(R.id.status); 
    textTriageStatus.setText(status); 
    text.setTextColor(Color.BLACK); 
    text.setText(msg); 
    Toast toast = new Toast(context); 
    toast.setView(toastRoot); 
    toast.setGravity(Gravity.TOP | Gravity.RIGHT, 0, 0); 
    toast.show(); 
} 

private void savePreferences(String key, int value) { 
    SharedPreferences sharedPreferences = getSharedPreferences(
      "APP_PREFERENCES", MODE_PRIVATE); 
    SharedPreferences.Editor editor = sharedPreferences.edit(); 
    editor.putInt(key, value); 
    editor.commit(); 
} 

private String loadPreferences(String key) { 
    SharedPreferences sharedPreferences = getSharedPreferences(
      "APP_PREFERENCES", MODE_PRIVATE); 
    String strSavedMem1 = sharedPreferences.getString(key, ""); 
    return strSavedMem1; 
} 

回答

0

您可以創建另一個類來處理這種情況,但你有因爲烤麪包和prefernces通過上下文處理通過上下文該方法。上下文將有許多類型1)應用程序2)活動3)服務4)廣播接收器。

> > public static void createCustomToast(Context context,String msg, String status) { 
>  >  LayoutInflater inflater = getLayoutInflater(); 
>  >  View toastRoot = inflater 
>  >    .inflate(R.layout.custom_toast_two_lines, null); 
>  >  TextView text = (TextView) toastRoot.findViewById(R.id.toastText); 
>  >  TextView textTriageStatus = (TextView) toastRoot 
>  >    .findViewById(R.id.status); 
>  >  textTriageStatus.setText(status); 
>  >  text.setTextColor(Color.BLACK); 
>  >  text.setText(msg); 
>  >  Toast toast = new Toast(context); 
>  >  toast.setView(toastRoot); 
>  >  toast.setGravity(Gravity.TOP | Gravity.RIGHT, 0, 0); 
>  >  toast.show(); } 
>  > 
>  > public static void savePreferences(Context context,String key, int value) { 
>  >  SharedPreferences sharedPreferences = context.getSharedPreferences(
>  >    "APP_PREFERENCES", MODE_PRIVATE); 
>  >  SharedPreferences.Editor editor = sharedPreferences.edit(); 
>  >  editor.putInt(key, value); 
>  >  editor.commit(); } 
>  > 
>  > public void String loadPreferences(Context context,,String key) { 
>  >  SharedPreferences sharedPreferences = context.getSharedPreferences(
>  >    "APP_PREFERENCES", MODE_PRIVATE); 
>  >  String strSavedMem1 = sharedPreferences.getString(key, ""); 
>  >  return strSavedMem1; } 
>  > 
>  > > Blockquote 
相關問題