【发布时间】:2015-01-18 12:47:25
【问题描述】:
我从 Fragment 创建了一个 DialogFragment,并在 Fragment 中实现了一个侦听器,问题是 DialogFragment 附加到 MainActivity 而不是父框架。
所以我在从片段调用的 DialogFragment 中有这段代码
// Override the Fragment.onAttach() method to instantiate the
// SensorRateChangeListener
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// Verify that the host activity implements the callback interface
try {
// Instantiate the SensorRateChangeListener so we can send events to
// the host
mListener = (SensorRateChangeListener) activity;
} catch (ClassCastException e) {
// The activity doesn't implement the interface, throw exception
throw new ClassCastException(activity.toString()
+ " must implement SensorRateChangeListener");
}
}
这是 Fragment 中调用对话框的代码
FragmentTransaction ft = getFragmentManager().beginTransaction();
Fragment prev = getFragmentManager().findFragmentByTag("dialog");
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
// Create and show the dialog.
DialogFragment newFragment = SensorRateChangeDlg.newInstance(mStackLevel);
newFragment.show(ft, "rate");
当我运行应用程序并创建 DialogFragment 时,它会因错误而崩溃......MainActivity 应该实现 SensorRateChangeListener,但它是在调用 Fragment 中实现的。
Error: MainActivity@424085b8 must implement SensorRateChangeListener
我无法在 MainActivity 中实现 SensorRateChangeListener 接口,因为它还有很多与 Fragment 相关的其他功能,这会使事情变得更加复杂。
【问题讨论】:
标签: java android android-activity android-fragments dialogfragment