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

时间:2017-10-06 12:05:28

标签: java android android-fragments classcastexception

我的#left { margin: auto; width: 30%; padding: 10px; float: left; height: auto; } #middle { margin: auto; width: 30%; padding: 10px; height: auto; } #right { margin: auto; width: 30%; padding: 10px; float: right; height: auto; } 中有一个RecyclerView。在每个RecyclerView行中,我有一个按钮,当按下它时,它应该打开一个带有RecyclerView列表的自定义片段对话框(这是一个多选对话框)。

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

我的问题:

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

ClassCastException

我的代码:

SecondActivity.java

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

PostsListAdapter.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");

CustomDialogFragment.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");

MultiDialogAdapter.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);
    }

}

DialogCommunicator.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;
    }

}

崩溃日志:

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$1.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.java中实现的界面。这是一个回调方法,因此我可以响应每个单独的操作,并知道在片段对话框弹出窗口中单击了哪个项目。

因此,我已经正确构建了对话框片段,因为它在列表外部的常规活动中工作,但对于RecyclerView列表中的每一行,该对话框片段因SecondActivity.java而崩溃了应用程序。为什么呢?

2 个答案:

答案 0 :(得分:3)

您可以使用parent.getContext().

在onCreateViewHolder中获取construtor,而不是将上下文作为对象传递

同样在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()传递给适配器,那么相应的活动必须实现接口DialogCommunicator,并且回调将转到活动而不是CustomDialogFragment

所以传递getContext()而不是getActivity(),因为CustomDialogFragment正在实现接口而不是活动。

答案 1 :(得分:2)

你的崩溃是非常明确的:

  

MainActivity无法投放到DialogCommunicator$Communicator

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

  

我有PostsListAdapter.javaSecondActivity.java实现的界面。

您有可能从implements DialogCommunicator.Communicator移除PostsListAdapter行,并将其添加到MainActivity(当然也可以移动实际的实现)。

原因在于:

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

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