在我的片段中,當我在recyclerView中選擇某種語言時,我想更新我的recyclerView。現在只有當我移動到另一個片段然後返回時才更新它。更新recyclerView
這是我的片段代碼:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_languages, container, false);
initViews(view);
initializeData();
initializeAdapter();
loadLocale();
return view;
}
protected void initViews(View view) {
recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
layoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), null));
}
public void loadLocale() {
String langPref = "Language";
SharedPreferences prefs = this.getActivity().getSharedPreferences("CommonPrefs", Activity.MODE_PRIVATE);
String language = prefs.getString(langPref, "");
changeLang(language);
}
@SuppressWarnings("deprecation")
public void changeLang(String lang) {
if (lang.equalsIgnoreCase(""))
return;
myLocale = new Locale(lang);
saveLocale(lang);
Locale.setDefault(myLocale);
android.content.res.Configuration config = new android.content.res.Configuration();
config.locale = myLocale;
getActivity().getBaseContext().getResources().updateConfiguration(config, getActivity().getBaseContext().getResources().getDisplayMetrics());
}
public void saveLocale(String lang) {
String langPref = "Language";
SharedPreferences prefs = this.getActivity().getSharedPreferences("CommonPrefs", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(langPref, lang);
editor.apply();
}
private void initializeData() {
languages = new ArrayList<>();
languages.add(new Languages(getString(R.string.english)));
languages.add(new Languages(getString(R.string.russian)));
languages.add(new Languages(getString(R.string.deutsch)));
languages.add(new Languages(getString(R.string.romana)));
}
private void initializeAdapter() {
LanguagesAdapter languagesAdapter = new LanguagesAdapter(languages, position -> {
String lang = "en";
switch (position) {
case 0:
lang = "en";
break;
case 1:
lang = "ru";
break;
case 2:
lang = "de";
break;
case 3:
lang = "ro";
break;
default:
break;
}
changeLang(lang);
});
recyclerView.setAdapter(languagesAdapter);
}
@SuppressWarnings("deprecation")
@Override
public void onConfigurationChanged(android.content.res.Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (myLocale != null) {
newConfig.locale = myLocale;
Locale.setDefault(myLocale);
getActivity().getBaseContext().getResources().updateConfiguration(newConfig, getActivity().getBaseContext().getResources().getDisplayMetrics());
}
}
在我的方法initializeAdapter我試着寫:
languagesAdapter.notifyDataSetChanged();
但這不起作用。
setAdapter方法,但我說的是沒有按將不起作用( – Morozov
它不會工作,因爲你沒有更新的數據集。該調用notifyDatasetChanged的要求是先更新你的實際數據集 – tompee
設置一個新創建的適配器後,直接調用notifyDatasetChanged實際上並沒有做任何有用的事情,只是強制重繪了這些項目,但是沒有改變數據 – tompee