在FragmentParentNewsDetail.java类中,我有一个ViewPager,然后我使用FragmentPagerAdapter将每个页面设置为相同的Fragment,如下所示:
@Override
public Fragment getItem(int position)
{
String newsId = this.myNewsIds.get(position);
Bundle bundle = new Bundle();
bundle.putInt(FragmentNewsDetail.NEWS_ID, Integer.parseInt(newsId));
FragmentNewsDetail fragmentNewsDetail = new FragmentNewsDetail();
fragmentNewsDetail.setArguments(bundle);
return fragmentNewsDetail;
}
在FragmentNewsDetail.java中,我有一个公共方法:
public String getNewsTitle()
{
Log.d(TAG, "getNewsTitle:" + newsTitle);
return newsTitle;
}
然后我想在FragmentNewsDetail.java中调用getNewsTitle()方法,如下所示:
newsTitle = ((FragmentNewsDetail)myAdapter.getItem(vpViewPager.getCurrentItem())).getNewsTitle();
但getNewsTitle()总是返回“”,我对此感到困惑。
通过以下方法修正:
public Fragment getCurrentFragment(ViewPager pager,
FragmentPagerAdapter adapter)
{
try
{
Method m = adapter
.getClass()
.getSuperclass()
.getDeclaredMethod("makeFragmentName", int.class,
long.class);
Field f = adapter.getClass().getSuperclass()
.getDeclaredField("mFragmentManager");
f.setAccessible(true);
FragmentManager fm = (FragmentManager) f.get(adapter);
m.setAccessible(true);
String tag = null;
tag = (String) m.invoke(null, pager.getId(),
(long) pager.getCurrentItem());
return fm.findFragmentByTag(tag);
}
catch (NoSuchMethodException e)
{
e.printStackTrace();
}
catch (IllegalArgumentException e)
{
e.printStackTrace();
}
catch (IllegalAccessException e)
{
e.printStackTrace();
}
catch (InvocationTargetException e)
{
e.printStackTrace();
}
catch (NoSuchFieldException e)
{
e.printStackTrace();
}
return null;
}
从:How to get existing fragments when using FragmentPagerAdapter
非常感谢!