2017-05-28 91 views
0

在我的片段中,當我在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(); 

但這不起作用。

回答

1

如果要更改回收站視圖的內容,則需要將新數據集加載到適配器。

LanguagesAdapter languagesAdapter = new LanguagesAdapter(...); 
recyclerView.setAdapter(languagesAdapter); 

另一種方法是更新適配器中的數據集對象並調用notifyDatasetChanged

+0

setAdapter方法,但我說的是沒有按將不起作用( – Morozov

+0

它不會工作,因爲你沒有更新的數據集。該調用notifyDatasetChanged的要求是先更新你的實際數據集 – tompee

+0

設置一個新創建的適配器後,直接調用notifyDatasetChanged實際上並沒有做任何有用的事情,只是強制重繪了這些項目,但是沒有改變數據 – tompee

0

而不是languagesAdapter.notifyDataSetChanged();請致電initializeAdapter();。讓我知道這是行不通的。

+0

我在recyclerView.setAdapter(languagesAdapter)後調用了此方法;和ofc不工作 - 遞歸調用。 – Morozov

0

我猜你想要在回收站列表視圖中點擊任何語言項目時翻轉/更改語言?如果是這種情況,您必須創建一個新的數據集,並將其添加到此列表中。像你從EN更改爲RU,那麼你有一個RU中的東西的清單是正確的?將該數據列表提供給點擊監聽器中的回收站視圖,然後從回收站視圖中獲取列表適配器並調用languagesAdapter.notifyDataSetChanged();

我在我的應用中也做過類似的事情。我們必須翻轉語言以查看阿拉伯語和英語視圖

+0

是的。你可以建議你自己實施這個問題,以便我可以改變自己的問題嗎?也許它會有用。 – Morozov

+0

將我的實現發佈爲新答案。 –

0

在onCreate on activity或onViewCreated fragment上設置UI元素的方法。

private void setupUI() { 
    tvTitle.setText(R.string.language_change_activity_title); 
    StaggeredGridLayoutManager mStaggeredLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL); 
    rvLanguageItems = (RecyclerView) findViewById(R.id.rv_language_items); 
    rvLanguageItems.setLayoutManager(mStaggeredLayoutManager); 
    rvLanguageItems.addItemDecoration(new SpaceItemDecoration(35, 35, 35, 35)); 
    // if we have already filled data one time then just load that data 

    // else request for new items 
    if (getInstance().getModel() != null) 
     setAdapter(getInstance().getModel()); //it gets instance of web service and take out data class and feed that to setAdapter method 
    else 
     requestForLanguageList(); // this method is just for requesting language items from web but you can use local list to update from 

    // Setup refresh listener which triggers new data loading 
    swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { 
     @Override 
     public void onRefresh() { 
      refreshFlag = true; 
      requestForLanguageList(); // web api call 
     } 
    }); 
} 

SetupUI呼籲填補數據和設置點擊聽衆

private void setAdapter(LanguageItemsModel languageItemsModel) { 
    if (refreshFlag) // this flag i used for cancel swipe to refresh 
     swipeLayout.setRefreshing(false); 
    // get adapter from recycler view 
    LanguageItemAdapter languageItemAdapter = (LanguageItemAdapter) rvLanguageItems.getAdapter(); 
    //if the adapter you got from recycler view is empty only then you fetch a new adapter other than that you just notify that data set has been changed 
    if (languageItemAdapter == null) { 
     languageItemAdapter = new LanguageItemAdapter(LanguageChangeActivity.this); 
     languageItemAdapter.addAll(languageItemsModel.getLanguage()); 
     rvLanguageItems.setAdapter(languageItemAdapter); 
    } else 
     languageItemAdapter.notifyDataSetChanged(); 
    rvLanguageItems.invalidate(); 
    //set item click Listener for recycler view 
    rvLanguageItems.addOnItemTouchListener(new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() { 
     @Override 
     public void onItemClick(View view, int position) { 

      if (Util.hasNetworkConnection(LanguageChangeActivity.this)) { 
       final LanguageItemAdapter languageItemAdapter = (LanguageItemAdapter) rvLanguageItems.getAdapter(); 
       //Change Language on Network as well as local 
       final Language languageClickedItem = languageItemAdapter.getCurrentClickedItem(view); 
       PreferenceManager preferenceManager = PreferenceManager.getInstance(); 
       int savedLanguageId = preferenceManager.read(LANGUAGE_ID, languageClickedItem.getLanguageId()); 
       if (savedLanguageId != languageClickedItem.getLanguageId()) { // only send request when user has clicked on some other language item then current set language item 

        ChangePreferenceRequestModel.getInstance().getData(LanguageChangeActivity.this, new WebServiceListener() { 
         @Override 
         public void onSuccess(Object response, String apiName) {//Save newly changed language prefrence 
           PreferenceManager preferenceManager = PreferenceManager.getInstance(); 
           preferenceManager.save(LANGUAGE_CODE, languageClickedItem.getLanguageCode()); 
           preferenceManager.save(LANGUAGE_ID, languageClickedItem.getLanguageId()); 
           // UpdateUI 
           languageItemAdapter.clearSelectedItems(); // clear selection from all items 
           languageClickedItem.setSelected(true); // set current item as selected 
           languageItemAdapter.notifyDataSetChanged(); // redraw screen 
         } 

         @Override 
         public void onError(Exception error, String apiName) { 
          Util.showToast(LanguageChangeActivity.this, LanguageChangeActivity.this.getString(R.string.exception_message), true); 
         } 

        }, changePreferenceRequestParameters, true, AppConstants.getLanguagePrefrenceChangeUrl()); 
       } 
      } else 
       Util.showToast(LanguageChangeActivity.this, LanguageChangeActivity.this.getString(R.string.no_connection), true); 
     } 
    })); 
}