当前位置: 首页 > 知识库问答 >
问题:

如果从片段调用DialogFragment会引发ClassCastException

汪弘毅
2023-03-14

如果从Fragment调用,我的DialogFragment会抛出ClassCastException,而如果从Activity调用,则会正常工作。我已经看了很少的其他问题与类似的问题,基本上是与进口有关的,但我没有能够解决在我的实现。下面是我对DialogFragment的实现。

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;

public class HotspotScanDialog extends DialogFragment {

    SetupHotspotDialogListener mListener;

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        ...

        .setAdapter(hotspotAdapter, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                mListener.onHotspotSelectedListener(hotspotAdapter.getItem(
                        which).toString());
            }
        })...
    }

    public interface SetupHotspotDialogListener {
        public void onHotspotSelectedListener(String selection);

    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        try {
            mListener = (SetupHotspotDialogListener) activity;
        } catch (ClassCastException ignore) {
            // Just to make sure if anyone will be pointing at my throwing
            // ClassCastException myself I have tried without this code as well.
            throw new ClassCastException(activity.toString()
                    + " must implement NoticeDialogListener");
        }
    }
}

下面是我使用上面的DialogFragment的片段:

import android.app.AlertDialog;
import android.app.DialogFragment;
import android.support.v4.app.Fragment;
import com.xxx.yyy.ui.compontent.dialog.HotspotScanDialog;
import com.xxx.yyy.ui.compontent.dialog.HotspotScanDialog.SetupHotspotDialogListener;

public class SmartMode extends Fragment implements SetupHotspotDialogListener {

    private void showWifiSelectionDialog() {
        DialogFragment setupWifiSelectionDialog = new HotspotScanDialog();

        /*
         * using getFragmentManager() only says "The method
         * show(FragmentManager, String) in the type DialogFragment is not
         * applicable for the arguments (FragmentManager, String)"
         */

        setupWifiSelectionDialog.show(getActivity().getFragmentManager(),
                Keys.TAG.toString());
    }

    @Override
    public void onHotspotSelectedListener(String selection) {
        // Log.d(TAG,selection);
    }
}

这是错误日志

我想知道有没有人能给出一个关于这个问题的提示。

共有1个答案

白子昂
2023-03-14

来自文档:

 onAttach(Activity) called once the fragment is associated with its activity.

在您的代码中

 mListener = (SetupHotspotDialogListener) activity;

行抛出ClassCastException,因为您的活动没有实现SetupHotSpotDialogListener接口。(fragment直接绑定到包含它的活动,以及dialogfragment,因为dialogfragment扩展了fragment)。

因此,如果您希望从fragment创建fragmentdialog,我建议通过回调到活动来组织它:

  1. 使用类似createDialogRequest()的方法在SmartModeFragment类中创建回调接口(就像在dialogFragment中所做的那样)。
  2. 让您活动实现该接口
  3. 然后,当您需要创建对话框时,将回调从片段发送到活动
  4. 将“显示对话逻辑”放入活动

它看起来像片段请求活动创建对话框,活动显示对话框。

编辑:我想我找到了更好的实现你所需要的。我编写了一个从片段创建fragment dialog并将fragment dialog回调事件接收到片段的简单示例。

活动:

public class MyFragmentActivity extends FragmentActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_fragment);

        // first start of activity
        if (savedInstanceState == null) {
            // put fragment to activity layout 
            MyFragment fragment = new MyFragment();
            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
            ft.replace(R.id.fragmentContainer, fragment, "fragment");
            ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
            ft.commit();
        }
    }

}
public class MyFragment extends Fragment implements MyDialogInterface {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);

        View fragmentView = inflater.inflate(R.layout.fragment, null);

        // button which shows dialog
        Button showDialogButton = (Button) fragmentView.findViewById(R.id.showDialog);
        showDialogButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // create fragment dialog.
                FragmentDialog dialog = FragmentDialog.getInstance(MyFragment.this);
                dialog.show(getActivity().getSupportFragmentManager(), "dialog");
            }
        });

        return fragmentView;
    }

    @Override
    public void onClickEvent() {
        // receive click events from dialog fragment
        Log.e(getClass().getSimpleName(), "onClickEvent");
    }

}

碎片对话框:

public class FragmentDialog extends DialogFragment {

    public interface MyDialogInterface extends Serializable {
        public void onClickEvent();
    }

    private MyDialogInterface callbackListener;

    /**
     * dialogInterface - instance of MyDialogInterface which will handle
     * callback events
     */
    public static FragmentDialog getInstance(MyDialogInterface dialogInterface) {
        FragmentDialog fragmentDialog = new FragmentDialog();

        // set fragment arguments
        Bundle args = new Bundle();
        args.putSerializable("dialogInterface", dialogInterface);
        fragmentDialog.setArguments(args);

        return fragmentDialog;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(STYLE_NO_TITLE, 0);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View pushDialogView = getActivity().getLayoutInflater().inflate(R.layout.fragment_dialog, null);

        // get reference to MyDialogInterface instance from arguments
        callbackListener = (MyDialogInterface) getArguments().getSerializable("dialogInterface");

        Button cancelButton = (Button) pushDialogView.findViewById(R.id.button);
        cancelButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // send click event
                callbackListener.onClickEvent();
            }
        });

        return pushDialogView;
    }

}

我使用了支持4库片段

android.support.v4.app.Fragment
android.support.v4.app.DialogFragment
android.support.v4.app.FragmentActivity

和布局:

activity_my_fragment.xml:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:id="@+id/fragmentContainer"
   android:layout_width="match_parent"
   android:layout_height="match_parent" />

fragment.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:background="#a00"
   android:orientation="vertical" >

   <Button
     android:id="@+id/showDialog"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:text="show doalog" />
</LinearLayout>

fragment_dialog.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:background="#fe3"
   android:orientation="vertical" >

   <Button
      android:id="@+id/button"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="click me" />
 </LinearLayout>
 类似资料:
  • 我有一个包含EditText的片段,当我单击该EditText时,会出现一个DatePicker对话框来选择日期。 FragmentFile 对话框片段 问题是我不知道如何将数据(选定日期)从DialogFraank传递到片段? 我读了一些主题,但这并没有帮助我感到困惑(抱歉再次提出这个问题)。 主题1主题2

  • 我正在尝试创建searchdate。我在这里做的是 下面是 所以首先,我打开,它是一个片段。然后单击(编辑文本)后,它将显示(DatePickerFragment)。显示没有问题,也没有错误。 我的问题是,我怎么能设置值后,我选择日期从我的?

  • 那么DialogFragments有什么特别之处呢?为什么在显示对话框时没有暂停调用片段?又如何实现呢? 我在文档中没有发现任何关于这种行为的引用,所以引用是一个加号。

  • 想象一下,我有FragmentA,我从它开始DialogFraank(框中有)。如何将中的值取回FragmentA?我尝试制作这样的东西,但我没有成功。

  • 我想从AlertDialog的setPositiveButton()方法内部的片段调用一个方法,该方法用于返回DialogFragment的对话框,但不能这样做。 我在一个名为Test的类中有doSomething()方法,该类扩展了Fragment。在这个类中,我有一个扩展DialogFragment的内部类。在方法onCreateDialog中,问题就发生在这里。查看代码: 对话片段和片段来自

  • 我有一个DialogFragment,它使用FragmentPagerAdapter来显示选项卡。每个选项卡都有一个使用RecyclerView的不同片段。我可以获取单击后传递给片段的项目,但如何才能将数据从片段获取到DialogFragment,以便将其传递给调用活动? TabDialog扩展DialogFraank: TabAdapter扩展了FragmentPagerAdapter 在Fra