对话框管理器(弹出窗口)消失后无法执行某些操作

Can't do something after dialog manager (pop up) disappear

我想在弹出窗口消失在片段中后做点什么。但是,我得到错误。请帮帮我..

Main.java

public class Main extends Fragment implements SendStringEvent{
    Button addButton;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.teacher_category, container, false); 
        addButton = (Button) rootView.findViewById(R.id.add_category_button);
        addButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                TEACHER_AddCategory teacherAddCategory = new TEACHER_AddCategory();
                teacherAddCategory.show(getFragmentManager(), "TEACHER_AddCategory");
            }
        });
       return rootView;
    }

    //This method from interface SendStringEvent
    @Override
    public void eventAfterMessageClosed(String message) {
        //I get error when executing this
        addButton.setText(message);
    }
}

TEACHER_AddCategory.java (弹出窗口)

public class TEACHER_AddCategory extends DialogFragment {
    Button OKButton;
    EditText editText;
    private SendStringEvent eventMessageClosed;
    Fragment fragment = new Main();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(seamolec.ujianonline.R.layout.teacher_add_category, container);
        OKButton = (Button) view.findViewById(seamolec.ujianonline.R.id.ok_button);
        try {
            eventMessageClosed = (SendStringEvent) fragment;
        }
        catch(ClassCastException e) {
            e.printStackTrace();
        }
        OKButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                    eventMessageClosed.eventAfterMessageClosed("test");
                    dismiss();
                }
            }
        });
        return view;
    }

}

这是界面SendStringEvent.java

 public interface SendStringEvent {
    void eventAfterMessageClosed(String message);
}

当弹出窗口消失并且系统正在执行时出现错误"eventAfterMessageClosed()"

日志猫:

发生这种情况是因为您正试图从一个甚至没有加载的新实例调用该方法,因此尚未创建视图。

改变

try {
        eventMessageClosed = (SendStringEvent) fragment;
    }
    catch(ClassCastException e) {
        e.printStackTrace();
    }

Fragment fr = getFragmentManager().findFragmentById(R.id.where_fragment_is_loaded) // Change as per you layout
if(fr != null && fr instanceOf SendStringEvent)
    eventMessageClosed = (SendStringEvent) fr;

并改变

eventMessageClosed.eventAfterMessageClosed("test");

if(eventMessageClosed != null)
    eventMessageClosed.eventAfterMessageClosed("test");

注意: R.id.where_fragment_is_loaded 是指示性的。使用您加载片段的 id Main。如果您正在使用支持库,也请使用 getSupportFragmentManager()