在活动中使用ArrayList作为内容的RecyclerView适配器在分区
我有这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
到使第一个片段中的列表显示添加的项目。
有很多方法可以做到这一点。一种方法是使FragmentOne
实现一个监听器。喜欢的东西:
public interface ContactsChangedListener {
void onContactsChanged();
}
public class FragmentOne implements ContactsChangedListener ... {
...
@Override
void onContactsChanged() {
ctcAdapter.NotifyDataSetChanged();
}
}
在FragmentTwo
,提供了一种通过监听器:
public class FragmentTwo ... {
...
private ContactsChangedListener mContactsChangedListener;
...
public void setContactsChangedListener(
ContactsChangedListener listener) {
mContactsChangedListener = listener;
}
}
,然后在MainActivity
onCreate
,你可以通过一个其他的接口:
@Override
protected void onCreate(Bundle savedInstanceState) {
...
fragmentOne = new FragmentOne();
...
fragmentTwo = new FragmentTwo();
fragmentTwo.setContactsChangedListener(fragmentOne);
contactsArrayList = new ArrayList<>();
...
}
这没什么奇特的。但它有诀窍,它保持封装。
非常感谢Michael,它完美的工作! – Rafael
如果您发布感兴趣的代码片段会更好。这会比用散文解释更好解释。 –