ClassCastException:使用 DialogFragment 时应用程序崩溃

ClassCastException: app crashes when using DialogFragment

我的 MainActivity.java 中有一个 RecyclerView。在每个 RecyclerView 行中,我都有一个按钮,当它被按下时,它应该会打开一个自定义的片段对话框,其中包含 RecyclerView 列表(这是一个多选对话框)。

在我的 SecondActivity.java 中,这是我的另一个 activity,我也有相同的按钮,它应该做同样的事情(这就是为什么我需要模态作为片段对话框).在我的SecondActivity.java里,没有RecyclerView,只有一个post(详情页)。

我的问题:

当我单击 SecondActivity.java 上的弹出窗口按钮时,它会正常打开对话框片段弹出窗口。当我对 RecyclerView(位于 MainActivity.java 中)中的任何单独行执行相同操作时,我收到 ClassCastException 错误:

java.lang.ClassCastException: com.example.appname.MainActivity cannot be cast to interfaces.DialogCommunicator$Communicator

我的代码:

SecondActivity.java

//*****************//
// THIS CODE WORKS //
//*****************//

// This code will run when the button is clicked.
// postOptions is a string array of menu items.
Bundle args = new Bundle();
args.putStringArray("displaymenu", postOptions);
mDialogFragment = new CustomDialogFragment();
mDialogFragment.setArguments(args);
mDialogFragment.show(getSupportFragmentManager(), "title");

PostsListAdapter.java

//***************************//
// THIS CODE CRASHES THE APP //
//***************************//

// This code is planted in onClick method listener in onBindViewHolder
// for the button that's supposed to open the fragment dialog.
FragmentManager fm = ((MainActivity) mContext).getSupportFragmentManager();
String[] items = mContext.getResources().getStringArray(R.array.post_options);
CustomDialogFragment customDialogFragment = CustomDialogFragment.newInstance(items);
customDialogFragment.show(fm, "title");

CustomDialogFragment.java

public class CustomDialogFragment extends DialogFragment {

    private RecyclerView mRecyclerView;

    public CustomDialogFragment() {
        // Empty constructor is required for DialogFragment
        // Make sure not to add arguments to the constructor
        // Use `newInstance` instead as shown below
    }

    public static CustomDialogFragment newInstance(String[] items) {
        CustomDialogFragment customDialogFragment = new CustomDialogFragment();
        Bundle args = new Bundle();
        args.putStringArray("displaymenu", items);
        customDialogFragment.setArguments(args);
        return customDialogFragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.layout_multiselect_dialog, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        Bundle args = getArguments();
        String[] items = args.getStringArray("displaymenu");
        List<String> itemsList = Arrays.asList(items);

        // THIS LINE CRASHES ON POSTSLISTADAPTER!!!
        MultiDialogAdapter adapter = new MultiDialogAdapter(getActivity(), itemsList);

        mRecyclerView = (RecyclerView) view.findViewById(R.id.items_recycler_view);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecyclerView.setAdapter(adapter);

        getDialog().setTitle(null);
    }

}

MultiDialogAdapter.java

public class MultiDialogAdapter extends RecyclerView.Adapter<MultiDialogViewHolder> {

    private List<String> mItems;
    private LayoutInflater mInflater;
    private CustomFonts mCustomFont;
    private DialogCommunicator.Communicator mCommunicator;

    public MultiDialogAdapter(Context context, List<String> items) {
        this.mInflater = LayoutInflater.from(context);
        this.mItems = items;
        this.mCustomFont = new CustomFonts(context);

        try {
            mCommunicator = (DialogCommunicator.Communicator) context;
        } catch (ClassCastException e) {
            // THIS IS WHERE THE CLASSCASTEXCEPTION HAPPENS!
            throw new ClassCastException(context.toString());
        }
    }

    @Override
    public MultiDialogViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = mInflater.inflate(R.layout.layout_multiselect_dialog_row, parent, false);
        return new MultiDialogViewHolder(view);
    }

    @Override
    public void onBindViewHolder(MultiDialogViewHolder holder, int position) {
        final String item = mItems.get(position);
        holder.getItemTextView().setText(item);
        holder.getItemTextView().setTypeface(mCustomFont.getPrimaryFontMedium());
        holder.getItemTextView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mCommunicator.onDialogButtonResponse(item);
            }
        });
    }

    @Override
    public int getItemCount() {
        return mItems.size();
    }

}

class MultiDialogViewHolder extends RecyclerView.ViewHolder {

    private TextView mItemTextView;

    public MultiDialogViewHolder(View rootView) {
        super(rootView);
        mItemTextView = (TextView) rootView.findViewById(R.id.item_text_view);
    }

    public TextView getItemTextView() {
        return mItemTextView;
    }

}

DialogCommunicator.java

public class DialogCommunicator {

    public interface Communicator {
        public void onDialogButtonResponse(String responseMessage);
    }

}

崩溃日志:

10-06 14:35:12.353 21683-21683/com.example.appname E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.appname, PID: 21683
java.lang.ClassCastException: com.example.appname.MainActivity@e06db1e
    at adapters.MultiDialogAdapter.<init>(MultiDialogAdapter.java:40)
    at fragments.CustomDialogFragment.onViewCreated(CustomDialogFragment.java:60)
    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1430)
    at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1740)
    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1809)
    at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:799)
    at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2580)
    at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2367)
    at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2322)
    at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2229)
    at android.support.v4.app.FragmentManagerImpl.run(FragmentManager.java:700)
    at android.os.Handler.handleCallback(Handler.java:751)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6776)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)

我有在 PostsListAdapter.javaSecondActivity.java 中实现的接口。这是一个回调方法,因此我可以响应每个单独的操作并知道在片段对话框弹出窗口中单击了什么项目。

所以,我已经正确构建了对话框片段,因为它在列表之外的正常 activity 中工作,但是对于 RecyclerView 列表中的每一行,该对话框片段使应用程序崩溃,因为 ClassCastException。为什么?

您可以使用 parent.getContext().

在 onCreateViewHolder 中获取构造函数,而不是将上下文作为对象传递

同样在 onBindViewholder 中你忘记了类型转换 viewholder.Add

MultiDialogViewHolder viewholder=(MultiDialogViewHolder)holder;

然后访问viewholder.getItemTextView().setText(item);

此外,在对适配器中的上下文进行打字之前,您的对话片段应该实现 DialogCommunicator。在对话片段

中添加 DialogCommunicator 的实现
public class CustomDialogFragment extends DialogFragment implements DialogCommunicator {

 //override the method
}

编辑:

发生错误的主要问题也是由于上下文。 这里传 MultiDialogAdapter adapter=new MultiDialogAdapter(getContext(), itemsList) .

如果您将 getActivity() 传递给适配器,那么您相应的 activity 必须实现接口 DialogCommunicator 并且回调到达 activity 而不是 CustomDialogFragment .

所以传递 getContext() 而不是 getActivity() 因为 CustomDialogFragment 正在实现接口而不是 activity.

你的崩溃非常明显:

MainActivity cannot be cast to DialogCommunicator$Communicator

根据您发布的内容,您尚未在 MainActivity 中实现此接口。你说:

I have that interface which is implemented in PostsListAdapter.java and SecondActivity.java.

很有可能您应该从 PostsListAdapter 中删除 implements DialogCommunicator.Communicator 行并将其添加到 MainActivity 中(当然还要移动实际的实现)。

具体原因是这一行:

MultiDialogAdapter adapter = new MultiDialogAdapter(getActivity(), itemsList);

您将 getActivity() 作为 Context 参数传递给适配器的构造函数。这很好,除了您的对话框的构造函数然后将此 Context 实例转换为您的界面。因此,每个可以显示此对话框的 Activity 都必须实现您的界面。