是否可以调用主 activity (Android) 中另一个 activity 的静态 class 中定义的方法?

Is it possible to call a method defined inside a static class of another activity in the main activity (Android)?

所以我有一个方法 loadLocale(),我想在 MainActivity 中使用它来设置存储在共享首选项中的用户首选语言。 SettingsActivity 代码如下所示:

public class SettingsActivity extends PreferenceActivity  {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        AppPreferenceFragment appPreferenceFragment=(AppPreferenceFragment)getFragmentManager().findFragmentByTag("PreferenceFragment");
        if(appPreferenceFragment==null)
            appPreferenceFragment = new AppPreferenceFragment();

        getFragmentManager()
                .beginTransaction()
                .replace(android.R.id.content, appPreferenceFragment, "PreferenceFragment")
                .commit();

    }


    public static class AppPreferenceFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener, Preference.OnPreferenceClickListener
    {
        
        @Override
        public void onCreate(final Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            loadLocale();
            //Some other code
            Preference pref_al = findPreference("select_app_language");
            pref_al.setOnPreferenceClickListener(this);
        }



        @Override
        public boolean onPreferenceClick(Preference preference) {
            //SOME CODE

            else if (preference.getKey().compareTo("select_pref_language")==0){
                setupSelectLanguageDialog();
            }
            return false;
        }



        public void setupAppLanguageDialog()
        {
            AlertDialog langChangeDialog;
            CharSequence[] changeLangList = {"English", "हिन्दी"};
            AlertDialog.Builder mBuilder = new AlertDialog.Builder(getActivity());
            mBuilder.setTitle("Choose language");
            mBuilder.setSingleChoiceItems(changeLangList, -1, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    if (i==0)
                    {
                        setLocale("en");
                        getActivity().recreate();
                    }
                    else
                    {
                        setLocale("hi");
                        getActivity().recreate();
                    }
                    dialogInterface.dismiss();
                }
            });
            langChangeDialog =mBuilder.create();
            langChangeDialog.show();

        }

        public void setLocale(String lang) {
            Locale locale = new Locale(lang);
            Locale.setDefault(locale);
            Configuration config = new Configuration();
            config.locale = locale;
            getResources().updateConfiguration(config ,getResources().getDisplayMetrics());

            DataRepository.setAppLanguage(lang);
            Log.v("locale",DataRepository.getUserData("app_lang"));
        }

        //load langauge saved in shared prefrences
        public void loadLocale()
        {
            String app_lang= DataRepository.getAppLanguage();

            if(InputValidator.isNullorEmpty(app_lang) || app_lang.equals(Constants.NO_DATA)){
                Log.v("Locale","Empty");
                return;
            }

            setLocale(app_lang);
            Log.v("loaded Locale",app_lang);
        }

我想在我的 mainActivity 中调用 loadLocale() 方法,以便在应用程序启动时默认选择首选语言。我的 mainActivity 看起来像:

public class MainActivity extends AppCompatActivity {

//Some declarations
@Override
protected void onCreate(Bundle savedInstanceState) {


    //I want to set my app language here by calling loadLocale()
    //loadLocale();

//other code

}

我可以在 MainActivity 中重新编写这两个函数。有更好的出路吗?

注意:DataRepository.getAppLanguage()DataRepository.setAppLanguage() 是通过 SharedPreferences

存储和获取应用程序语言的方法

从语法上讲,您应该可以通过调用 new SettingsActivity.AppPreferenceFragment().loadLocale(); 来实现您的目标,因此您的 MainActivity 将如下所示:

public class MainActivity extends AppCompatActivity {

    //Some declarations
    @Override
    protected void onCreate(Bundle savedInstanceState) {


        //I want to set my app language here by calling loadLocale()
        AppPreferenceFragment appPreferenceFragment=(AppPreferenceFragment)getFragmentManager().findFragmentByTag("PreferenceFragment_MainActivity");
        if(appPreferenceFragment==null)
            appPreferenceFragment = new AppPreferenceFragment();

        getFragmentManager()
            .beginTransaction()
            // have a hidden framelayout as flPrefContent in the XML file attached with this activity
            .replace(R.id.flPrefContent, appPreferenceFragment, "PreferenceFragment_MainActivity")
            .commit();
        appPreferenceFragment.loadLocale();

        //other code

    }
}

但是正如@najm 在 中建议的那样,您应该在可能是单例class 中提取此类逻辑,并使用loadLocale()setLocale() 等方法class 来自您应用中的任何位置,例如 MainActivitySettingsActivity 等等。

为什么你不只用静态函数制作一个 Class,如果需要传递参数,如果需要添加 return 类型。然后你可以从任何地方调用它。示例:

class Helper {
    public static void loadLocale(Context context)
    {
        String app_lang= DataRepository.getAppLanguage();

        if(InputValidator.isNullorEmpty(app_lang) || app_lang.equals(Constants.NO_DATA)){
            Log.v("Locale","Empty");
            return;
        }

        setLocale(app_lang, context);
        Log.v("loaded Locale",app_lang);
    }

    public static void setLocale(String lang, Context context) {
        Locale locale = new Locale(lang);
        Locale.setDefault(locale);
        Configuration config = new Configuration();
        config.locale = locale;
        context.getResources().updateConfiguration(config ,context.getResources().getDisplayMetrics());

        DataRepository.setAppLanguage(lang);
        Log.v("locale",DataRepository.getUserData("app_lang"));
    }
}