0

我正在尝试按照此说明https://stackoverflow.com/a/14808425/2933117从 DialogFragment 返回一个字符串,但我只收到 logcat 错误

java.lang.ClassCastException: com.example.testinterface.MainActivity cannot be cast to com.example.testinterface.InterDialog$EditNameDialogListener

感谢任何帮助或解释为什么我会出错,在此先感谢。

这是我的代码:

主要活动

public class MainActivity extends FragmentActivity {

    private Button Btn;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Btn=(Button)findViewById(R.id.button1);

        Btn.setOnClickListener(new View.OnClickListener(){
            public void onClick (View view) {
                FragmentManager fm = getSupportFragmentManager();
                InterDialog pruebafragment = new InterDialog();
                pruebafragment.show(fm,"MyFragment");
            }
        });

    }

    public void onFinishEditDialog (String inputText) {
        Toast.makeText(this, "Hi, " + inputText, Toast.LENGTH_SHORT).show();
    }

}

DialogFragment

public class InterDialog extends DialogFragment {

    public interface EditNameDialogListener {
        void onFinishEditDialog(String inputText);
    }

    public InterDialog() {
        // Empty constructor required for DialogFragment
    }

    EditNameDialogListener activity;

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

     View view = inflater.inflate(R.layout.new_layout, container);  

     activity = (EditNameDialogListener) getActivity(); 

     Button button = (Button)view.findViewById(R.id.Btnreturn);
     button.setOnClickListener(new OnClickListener() {
         public void onClick(View v) {
             activity.onFinishEditDialog("errorrrr");
             getDialog().dismiss();
         }
     });

     return view;

  }
}
4

1 回答 1

2

该行:

activity = (EditNameDialogListener) getActivity();

是什么打破了它。确保您的活动通过执行来实现 EditNameDialogListener 接口

public class MainActivity extends FragmentActivity implements EditNameDialogListener {

希望有帮助

于 2013-10-30T17:18:00.737 回答