我有一个使用Android支持框架的ViewPager,它支持三个片段。用户可以通过滑动在它们之间导航。
第二个片段包含两个GridView,每个GridView都使用适配器填充按钮。
这两个GridView被命名为(在XML中)left_buttons和right_buttons。 left_buttons由扩展BaseAdapter的CategoryAdapter控制,right_buttons由ItemAdapter控制,也扩展了BaseAdapter。
我遇到的问题是,当用户点击CategoryAdapter中的按钮时,我想在ItemAdapter上调用notifyDataSetChanged(),然后在关联的GridView上调用invalidateViews()。因为这两个适配器是在同一个片段MenuFragment中创建的,所以我很难找到最佳的通信方式。
我已经看到很多关于片段之间,片段和活动之间的通信的答案,等等。我尝试从CategoryAdapter中获取对R.id.right_buttons的引用,但找不到解决方案(因为无法访问findViewById等)。
然后,我读了一些建议我需要在Fragment中创建方法的答案,所以我在MenuFragment.class中尝试了以下内容:
public void updateRightGrid() {
//grab a reference to the right hand grid right_buttons
GridView rightButtons = (GridView) getView().findViewById(R.id.right_buttons);
//get the adapter that is controlling right_buttons
ItemAdapter menuItemAdapter = (ItemAdapter) rightButtons.getAdapter();
//tell this adapter that we have some new data, so please refresh
menuItemAdapter.notifyDataSetChanged();
//force the grid to refresh
rightButtons.invalidateViews();
}
问题是我仍然找不到从CategoryAdapter调用此方法的方法。我已经创建了一个实现OnClickListener的内部类,并且在public void onClick(View v)中我试图调用该片段的方法updateRightGrid()。我可以通过变量mContext访问上下文,但这似乎没有帮助。
非常感谢任何帮助!
答案 0 :(得分:0)
您的适配器中可能包含活动的上下文,因此您可以在以下活动中创建方法:
//your activity code
public void notifyItemAdapter() {
itemAdapter.notifyDataSetChanged() ;
}
然后在你的CategoryAdapter中:
//adapter code
activityContext.notifyItemAdapter();