4

我有这部分代码用于对话片段

public class DialogOne extends DialogFragment  {
private Button b;

public DialogOne() {}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.dialog_one, container);
    getDialog().setTitle("Titolo del dialog");
    b = (Button)getDialog().findViewById(R.button.ok);
    b.setOnclickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    getDialog().dismiss();
                }
            });

    return view;
}

所以当我按下按钮时,dialogfragment 必须关闭。当我运行应用程序时,我在行上有一个 NullPoinerException,包含新的 OnClickListener。我该如何解决?

> 02-28 21:05:44.623: E/AndroidRuntime(8487): FATAL EXCEPTION: main
02-28 21:05:44.623: E/AndroidRuntime(8487): java.lang.NullPointerException
02-28 21:05:44.623: E/AndroidRuntime(8487):     at com.example.dialogs.DialogOne.onActivityCreated(DialogOne.java:37)
02-28 21:05:44.623: E/AndroidRuntime(8487):     at android.support.v4.app.Fragment.performActivityCreated(Fragment.java:1468)
02-28 21:05:44.623: E/AndroidRuntime(8487):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:931)
02-28 21:05:44.623: E/AndroidRuntime(8487):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1088)
02-28 21:05:44.623: E/AndroidRuntime(8487):     at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
02-28 21:05:44.623: E/AndroidRuntime(8487):     at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1444)
02-28 21:05:44.623: E/AndroidRuntime(8487):     at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:429)
02-28 21:05:44.623: E/AndroidRuntime(8487):     at android.os.Handler.handleCallback(Handler.java:725)
02-28 21:05:44.623: E/AndroidRuntime(8487):     at android.os.Handler.dispatchMessage(Handler.java:92)
02-28 21:05:44.623: E/AndroidRuntime(8487):     at android.os.Looper.loop(Looper.java:137)
02-28 21:05:44.623: E/AndroidRuntime(8487):     at android.app.ActivityThread.main(ActivityThread.java:5041)
02-28 21:05:44.623: E/AndroidRuntime(8487):     at java.lang.reflect.Method.invokeNative(Native Method)
02-28 21:05:44.623: E/AndroidRuntime(8487):     at java.lang.reflect.Method.invoke(Method.java:511)
02-28 21:05:44.623: E/AndroidRuntime(8487):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
02-28 21:05:44.623: E/AndroidRuntime(8487):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
02-28 21:05:44.623: E/AndroidRuntime(8487):     at dalvik.system.NativeStart.main(Native Method)
4

1 回答 1

8

我想你想换

b = (Button)getDialog().findViewById(R.button.ok);

b = (Button) view.findViewById(R.button.ok);

于 2013-02-28T20:03:20.970 回答