gpt4 book ai didi

android - 无法在 dialogfragment 中的按钮上获取指针

转载 作者:搜寻专家 更新时间:2023-11-01 09:39:58 25 4
gpt4 key购买 nike

我正在尝试构建一个简单的 DialogFragment,其中包含一个 TextView 和两个按钮(发送和取消)。

我想在 textview 第一次为空时禁用按钮,但代码中的 positiveButton 变量始终为 null,并且出现以下异常:

 java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setEnabled(boolean)' on a null object reference

这是代码:

public class SendFriendRequestFragment extends DialogFragment {
private TextView tvEmail = null;
Button positiveButton = null;

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

// Get the layout inflater
final LayoutInflater inflater = getActivity().getLayoutInflater();

final View layout = inflater.inflate(R.layout.fragment_send_friend_request, null);

// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(layout)
.setTitle("Send request")
.setPositiveButton(R.string.send, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
String email = tvEmail.getText().toString().trim();

if (validateInput()) {
SendFriendRequest(getActivity(), email);
} else {
Toast.makeText(getActivity(), "Request cannot be sent", Toast.LENGTH_LONG).show();
return;
}

}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});

Dialog dialog = builder.create();
positiveButton = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE);

positiveButton.setEnabled(false); // positiveButton is null and this call raises an exception !
tvEmail = (TextView) layout.findViewById(R.id.email);
tvEmail.addTextChangedListener(new InputTextWatcher(tvEmail));
// Create the AlertDialog object and return it
//return builder.create();
return dialog;
}
// Other functions that use the two variables positiveButton and tvEmail ...
}

谁能告诉我如何解决我的问题,以及获取所用布局中包含的按钮和 View 指针的最佳方法是什么?

谢谢!

最佳答案

在显示 Dialog 之前,不会真正创建肯定的 Button。由于您在 DialogFragment 中,因此您不会直接处理 Dialog 上的 show() 调用。您可以在 AlertDialog 上设置一个 OnShowListener,但在 DialogFragment 中获取 Button 可能更简单s onStart() 方法。

@Override
public void onStart() {
super.onStart();

positiveButton = ((AlertDialog) getDialog()).getButton(AlertDialog.BUTTON_POSITIVE);
...
}

关于android - 无法在 dialogfragment 中的按钮上获取指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40456670/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com