我有這Activity
裏面有兩個片段在TabLayout。在活動中使用ArrayList作爲內容的RecyclerView適配器在分區
在我的Activity
有一個靜態的ArrayList
。 我是我的拳頭Fragment
,我們稱之爲FragmentOne
我有一個RecyclerView
和第二個Fragment
,FragmentTwo
我在哪裏我需要魔法發生。
在FragmentTwo
,我打電話給我Activity
同樣的ArrayList
,並添加一個或多個項目。在FragmentOne
我也打電話給ArrayList
,並將其值傳遞給我的RecyclerView
的適配器中使用的非靜態ArrayList
。
我怎麼能在我的第二個Fragment
調用這個方法我FragmentOne
的RecyclerView
的notifyDataSetChanged()
,所以RecyclerView
將更新它的內容?
或者有一個更有效的方式發送項目到我的拳Fragment
ArrayList
,我用我的RecyclerView Adapter
?
我的活動:
public class MainActivity {
TabLayout tabLayout;
ViewPager viewPager;
ViewPagerAdapter viewPagerAdapter;
FragmentOne fragmentone;
// The ArrayList used as FragmentOne RecyclerView's Adapter
public static ArrayList<Contacts> contactsArrayList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragmentOne = new FragmentOne();
contactsArrayList = new ArrayList<>();
}
}
FragmentOne RecyclerView:
public class FragmentOne extends Fragment implements View.OnClickListener {
// RecyclerView's adapter
ContactsAdapter ctcAdapter;
// RecyclerView
RecyclerView rvContacts;
public FragmentOne() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_one, container, false);
// RecyclerView
rvContacts = (RecyclerView) view.findViewById(R.id.rvContacts);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
rvContacts.setLayoutManager(linearLayoutManager);
// Here I'm adding the static list from the Main Activity in the adapter
ctcAdapter = new ContactsAdapter(getContext(), MainActivity.contactsArrayList);
rvContacts.setAdapter(ctcAdapter);
return view;
}
}
我唯一需要的是如何調用ctcAdapter.notifyDataSetChanged()
在我的第二個片段後,我添加了一個新的項目到contactsArrayList
到使第一個片段中的列表顯示添加的項目。
如果您發佈感興趣的代碼片段會更好。這會比用散文解釋更好解釋。 –