简体   繁体   中英

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

So I have a method loadLocale() which I want to use in the MainActivity to set user preferred language stored in shared preferences. The SettingsActivity code looks like below:

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

I want to call loadLocale() method in my mainActivity so that when the application starts, the preferred language is selected by default. My mainActivity looks like:

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

}

I can re-write both the functions again the MainActivity to do so. Is there a better way out?

NOTE: DataRepository.getAppLanguage() and DataRepository.setAppLanguage() are methods to store and get app language via SharedPreferences

Syntactically, you should be able to achieve your target by calling new SettingsActivity.AppPreferenceFragment().loadLocale(); , so your MainActivity will look like the following:

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

    }
}

But as @najm has suggested in the comment , you should extract such logics in probably a singleton class and use methods as loadLocale() , setLocale() etc. of that class from anywhere in your app like in MainActivity , SettingsActivity and so on.

Why you don't just make a Class with only static functions, passing Parameters if needed and add return type if needed. Then you can call it from anywhere. Example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM