gpt4 book ai didi

java - 如何创建一个单独的类来处理 android 常见任务,例如创建进度对话框?

转载 作者:行者123 更新时间:2023-11-29 09:00:34 25 4
gpt4 key购买 nike

我是新手,我正在编写一个简单的 Android 应用程序,其中包含多个 Activity。在每个 Activity 中,我都必须使用进度对话框和自定义布局 Toast。我还必须在其中一些中保存和加载首选项。我怎样才能将所有这些方法放在一个单独的类中,我不想在每个 Activity 中都编写相同的代码。它可以是静态类吗?

谢谢。

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

最佳答案

您可以创建另一个类来处理这种情况,但您必须将上下文传递给该方法,因为 toast 和首选项由上下文处理。上下文将有多种类型 1)Application 2)Activity 3)Service 4)Broadcast Receiver。

> >  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

关于java - 如何创建一个单独的类来处理 android 常见任务,例如创建进度对话框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17765113/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com