我的对话片段有问题。我想使用 android:onClick 属性,因为我认为代码更清晰。
在我的布局中,我有以下声明:
<Button
android:id="@+id/dialog_new_database_button_cancel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="@string/button_cancel"
android:maxLines="1"
style="?android:attr/buttonBarButtonStyle"
android:onClick="buttonCancel"
/>
现在我的 DialogFragment
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class DialogNewDatabase extends DialogFragment {
public DialogNewDatabase() {
// Empty constructor required for DialogFragment
super();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView (inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.dialog_new_database, container);
getDialog().setTitle("Hello");
return view;
}
@Override
public void onCreate(Bundle bundle) {
setCancelable(true);
setRetainInstance(true);
super.onCreate(bundle);
}
@Override
public void onDestroyView() {
if (getDialog() != null && getRetainInstance())
getDialog().setDismissMessage(null);
super.onDestroyView();
}
public void buttonCancel (View view) {
dismiss();
}
public void buttonOK (View view) {
}
}
现在,当我尝试单击取消按钮时,我得到:
java.lang.IllegalStateException: Could not find a method buttonCancel(View) in the activity class android.view.ContextThemeWrapper for onClick handler on view class android.widget.Button with id 'dialog_new_database_button_cancel'
at android.view.View$1.onClick(View.java:3031)
at android.view.View.performClick(View.java:3511)
at android.view.View$PerformClick.run(View.java:14105)
at android.os.Handler.handleCallback(Handler.java:605)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4482)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:787)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:554)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NoSuchMethodException: buttonCancel [class android.view.View]
at java.lang.Class.getConstructorOrMethod(Class.java:460)
at java.lang.Class.getMethod(Class.java:915)
at android.view.View$1.onClick(View.java:3024)
... 11 more
任何的想法?这可能与我使用 import android.support.v4.app.DialogFragment (support v4) 的事实有关吗?如何解决这个问题(我仍然更喜欢在 xml 布局中使用 android:onClick)。