简体   繁体   中英

Refresh Activity from ViewPager Fragment

I have a BaseActivity which has a ViewPager with some Fragments in it. In one of these Fragments I have 2 buttons which change the language of the app. The thing I want to accomplish is that, on the click of the button, refresh BaseActivity to the selected language but still have the ViewPager set on Settings(name of the fragment). Right now it's reloading the entire app and starts on the fragment which I set it to start on.

Code for changing the language and refreshing the Activity

 public void setLocale(String lang) {
        Locale myLocale = new Locale(lang);
        Resources res = getResources();
        DisplayMetrics dm = res.getDisplayMetrics();
        Configuration conf = res.getConfiguration();
        conf.locale = myLocale;
        res.updateConfiguration(conf, dm);
        SharedPreferences ensharedPreferences = getActivity().getSharedPreferences("selectedLanguage", MODE_PRIVATE);
        SharedPreferences.Editor eneditor = ensharedPreferences.edit();
        eneditor.putString("language", lang);
        eneditor.apply();
        SharedPreferences pref = getActivity().getSharedPreferences(lang,MODE_PRIVATE);
        Intent refresh = new Intent(getContext(), BaseActivity.class);
        getActivity().overridePendingTransition(0,0);
        startActivity(refresh);
        getActivity().overridePendingTransition(0,0);
    }

I have only found methods on doing this the reverse way, to reload a fragment from the activity, but I want to do it the other way.

You can pass the ViewPager's selected position to the Activity using getCurrentItem() and pass it to the new Intent as an extra and reselect the item number when relaunching the Activity through getIntent() and move to the previously selected Fragment by using setCurrentItem(int position)

// Restarting the Activity passing the position of the currently selected Fragment
Intent intent = new Intent(getContext(), BaseActivity.class);
intent.putExtra(EXTRA_POSITION, viewPager.getCurrentItem());
startActivity(intent);

@Override
protected void onCreate(Bundle savedInstanceState) {
   ...
   Intent intent = getIntent();
   if(intent != null) {
      int position = intent.getIntExtra(EXTRA_POSITION, 0);
      viewPager.setCurrentItem(position);
   }
}

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