我正在尝试按照说明https://stackoverflow.com/a/14808425/2933117从DialogFragment返回一个String,但我只收到logcat错误
java.lang.ClassCastException: com.example.testinterface.MainActivity cannot be cast to com.example.testinterface.InterDialog$EditNameDialogListener
我感谢任何帮助或解释为什么我会收到错误,提前谢谢。
这是我的代码:
MainActivity
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;
}
}
答案 0 :(得分:2)
该行:
activity = (EditNameDialogListener) getActivity();
是打破它的原因。通过执行
确保您的活动实现EditNameDialogListener接口public class MainActivity extends FragmentActivity implements EditNameDialogListener {
希望有所帮助