![](/img/trans.png)
[英]notifyDataSetChanged() to the recyclerView from an outer class
[英]RecyclerView notifydatasetchanged not invoked from fragment
我有一個家庭活動和 3 個子片段,在家庭活動中,我被調用了一個 api,然后我想將結果更新到片段中包含的回收器視圖。 現在除了 notifydatasetchanged() 之外的所有內容都運行良好。
你有任何關於片段的想法,請幫助我。
家庭活動.java
// member variable for the first fragment
private FeedsFragment feedsFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
// initialised in oncreate
feedsFragment = new FeedsFragment();
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(feedsFragment, "FEEDS");
}
// this is what i am called when get the api result
feedsFragment.setUpdateArrayList(updateArrayList);
FeedsFragment.java
public class FeedsFragment extends Fragment {
private RecyclerView recyclerView;
private UpdateListAdapter uAdapter;
private ArrayList<Updates> updateArrayList;
private String TAG = UpdatesActivity.class.getSimpleName();
public FeedsFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
updateArrayList = new ArrayList<Updates>();
View thisView = inflater.inflate(R.layout.activity_updates, container, false);
recyclerView = (RecyclerView) thisView.findViewById(R.id.recycler_view_updates);
uAdapter = new UpdateListAdapter(getActivity(), updateArrayList, new UpdateListAdapter.UpdatesActionListener() {
@Override
public void onShareButtonTapped(int position) {
}
@Override
public void onOptionsButtonTapped(int position, View v) {
}
@Override
public void onProfileButtonTapped(int position) {
}
});
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(uAdapter);
return thisView;
}
public void setUpdateArrayList(ArrayList<Updates> array){
this.updateArrayList = array;
this.recyclerView.getAdapter().notifyDataSetChanged();
//Also tried
// uAdapter.notifyDataSetChanged();
}
}
問題是您更改了片段中的updateArrayList
而不是適配器中的列表。
您可以在UpdateListAdapter
添加一個 api 作為
public void setData(List<Updates> data){...}
然后調用該API setUpdateArrayList
致電前notifyDataSetChanged
。
謝謝支持,問題暫時通過重新初始化upadadatelistadapter解決
public void setUpdateArrayList(ArrayList<Updates> array){
this.updateArrayList = array;
********** <Reinitialized the adapter here >**********
this.recyclerView.getAdapter().notifyDataSetChanged();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.