【发布时间】:2014-07-13 16:30:10
【问题描述】:
我有一个 ViewPager 片段实例化一个 DialogFragment。因为 Android 开发者指南说...
"所有 Fragment 到 Fragment 的通信都是通过关联的 活动。两个 Fragment 永远不应该直接通信。”
...此 DialogFragment 向 MainActivity 提供回调,然后将该信息向下馈送到 ViewPager 片段。
我的 DialogFragment "ModeDialogFragment" 从 onClick 中调用以下方法:
((MainActivity)getActivity()).updateData();
MainActivity 中的 updateData 方法识别 ViewPager 片段“MyFragment”并启动方法 doUpdateData()。
public void updateData(){
// Call function that generates the correct tab to identify MyFragment
MyFragment myFrag = (MyFragment) findFragmentByPosition(3); // Exception occurs here
myFrag.doUpdateData();
}
public Fragment findFragmentByPosition(int position) {
int viewId = R.id.pager
return getSupportFragmentManager().findFragmentByTag(
makeFragmentName(viewId, position));
}
String makeFragmentName(int viewId, int position)
{
return "android:switcher:" + viewId + ":" + position;
}
但是,当我运行代码时,我得到以下 ClassCastException:
07-13 01:19:53.972: E/AndroidRuntime(1660): java.lang.ClassCastException: com.example.myapp.ModeDialogFragment cannot be cast to com.example.myapp.MyFragment
(如果被问到,我可以提供其余的。)我知道如果它们完全不同,它们就不能被视为相同,但是为什么 ModeDialogFragment 会干扰呢? findFragmentByPosition() 没有返回 ModeDialogFragment,我不明白为什么 MainActivity 应该抱怨。唯一的联系是 ModeDialogFragment 正在执行调用。我对此很陌生,所以我是否有可能错误地进行回调?
编辑: 一些额外的代码。 这是我的 ViewPagerAdapter:
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int index) {
switch (index) {
case 0:
// Fragment0 tab
return new Fragment0();
case 1:
// Fragment1 tab
return new Fragment1();
case 2:
// Fragment2 tab
return new Fragment2();
case 3:
// MyFragment tab
return new MyFragment();
}
return null;
}
@Override
public int getCount() {
// get item count - equal to number of tabs
return 4;
}
}
这就是我如何通过单击 ListView 项来启动 ModeDialogFragment、扩展 Fragment:
myList.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
public void onItemClick(AdapterView<?> parentAdapter, View view, int position, long id)
{
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ModeDialogFragment modeDialog = ModeDialogFragment.newInstance(R.string.mode_calibration);
String title = makeFragmentName(R.id.pager, 3); // As in MainActivity. Takes ViewPager ID and fragment number.
//ft.add(modeDialog, title);
modeDialog.show(ft, title);
}
}
【问题讨论】:
-
我有一个 ViewPager 片段实例化一个 DialogFragment。 - 是
ModeDialogFragment用作ViewPager中的一个页面,或者你只是从其中一个页面开始(作为旁注ViewPager从0开始页数)?我看到你用例外标记了这条线,你确定它发生在那里(只是为了绝对确定)?另外,请不要在您的问题标题前加上标签名称作为android,底部的标签足以显示问题的范围。 -
(关于标签,我会记住这一点,我不知道。谢谢。)DialogFragment 本身不是一个页面,它只是显示在顶部并开始从第 4 页开始(所以计数为 3)。我确定这是发生异常的行 - 至少,它是 LogCat 指定的行。
-
你能贴出寻呼机适配器的代码吗?
-
适配器本身的代码,还是分页器片段中的对话框实例化?
-
发布两者以查看您在做什么。
标签: android android-fragments callback android-dialogfragment