DialogFragment抛出ClassCastException - 如果从片段称为(Dial

2019-08-16 16:44发布

我DialogFragment抛出ClassCastException -如果从片段调用,而它正常工作,如果从一个活动叫。 我已经看过类似的问题,基本上这些都与进口一些其他的问题,但我一直没能解决它在我的实现。 这里是我实施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);
    }
}

这是错误日志:

02-01 13:11:32.750:E / AndroidRuntime(15061):致命异常:主02-01 13:11:32.750:E / AndroidRuntime(15061):java.lang.ClassCastException:com.milanix.tuki.UiMainActivity @ 41d75350必须实现NoticeDialogListener 02-01 13:11:32.750:E / AndroidRuntime(15061):在com.xxx.yyy.ui.compontent.dialog.HotspotScanDialog.onAttach(HotspotScanDialog.java:122)02-01 13:11: 32.750:E / AndroidRuntime(15061):在android.app.FragmentManagerImpl.moveToState(FragmentManager.java:787)02-01 13:11:32.750:E / AndroidRuntime(15061):在android.app.FragmentManagerImpl.moveToState(FragmentManager的.java:1035)02-01 13:11:32.750:E / AndroidRuntime(15061):在android.app.BackStackRecord.run(BackStackRecord.java:635)02-01 13:11:32.750:E / AndroidRuntime(15061 ):在android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1397)02-01 13:11:32.750:E / AndroidRuntime(15061):在android.app.FragmentManagerImpl $ 1.run(FragmentManager.java:426)02 -01 13:11:32.750:E / AndroidRuntime(15061):在android.os.Handl er.handleCallback(Handler.java:615)02-01 13:11:32.750:E / AndroidRuntime(15061):在android.os.Handler.dispatchMessage(Handler.java:92)02-01 13:11:32.750: E / AndroidRuntime(15061):在android.os.Looper.loop(Looper.java:137)02-01 13:11:32.750:E / AndroidRuntime(15061):在android.app.ActivityThread.main(ActivityThread.java :4898)02-01 13:11:32.750:E / AndroidRuntime(15061):在java.lang.reflect.Method.invokeNative(本机方法)02-01 13:11:32.750:E / AndroidRuntime(15061):在java.lang.reflect.Method.invoke(Method.java:511)02-01 13:11:32.750:E / AndroidRuntime(15061):在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java :1006)02-01 13:11:32.750:E / AndroidRuntime(15061):在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)02-01 13:11:32.750:E / AndroidRuntime (15061):在dalvik.system.NativeStart.main(本机方法)

我想知道如果任何人都可以给这个问题的提示。

Answer 1:

从文档 :

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

在您的代码

 mListener = (SetupHotspotDialogListener) activity;

行抛出ClassCastException ,因为你的活动没有实现SetupHotspotDialogListener接口。 ( Fragment直接连接到包含它的活性,以及DialogFragment因为DialogFragment延伸Fragment )。

再从文档

在某些情况下,你可能需要一个片段与大家分享的活动事件。 要做到这一点的一个好方法是定义片段内的回调接口,并要求该主机活动实现它。 当活动通过所述接口接收的回调,它可以共享在根据需要布局的其它片段的信息。

所以,如果你想创建FragmentDialogFragment ,我建议通过回调来活动的安排是:

  1. 创建回调接口到您的SmartMode Fragment类(像你一样成dialogFragment)有了这样一个方法createDialogRequest()
  2. 让你的活动实现该接口
  3. 那么,当你需要创建对话框中,从发送回调FragmentActivity
  4. 将“显示对话框逻辑”为Activity

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

编辑:我想我已经找到了更好地执行你所需要的。 我已经写创建一个简单的例子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");
    }

}

FragmentDialog:

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>

这个想法是送参考接口,该接口将捕捉回调事件。



Answer 2:

public class HotspotScanDialog extends DialogFragment {
    ...
    SetupHotspotDialogListener mListener;
    ...
    @Override
    public void onAttachFragment(Fragment childFragment) {
        super.onAttachFragment(childFragment);
        mListener = (SetupHotspotDialogListener) childFragment;
    }
    ...
}

和内部片段这就要求DialogFragment:

HotspotScanDialog dialog = new HotspotScanDialog();
dialog.show(getChildFragmentManager(), "TAG");


文章来源: DialogFragment throws ClassCastException if called from Fragment