2013-07-20 18 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 
相关问题