Android: получить значение EditText из DialogBox с пользовательским представлением
У меня есть диалоговое окно, созданное с использованием класса AlertDialog.Builder и вызовом builder.setView(int resource), чтобы дать ему собственный макет для ввода текста.
Я пытаюсь получить значения из EditTexts на макете, когда пользователь нажимает кнопку ОК, но при вызове findViewByID() я получаю нулевые ссылки. Читая вокруг, кажется, что это происходит в другом месте, если кто-то пытается загрузить View перед вызовом setContentView(). С помощью Builder я, очевидно, не сделал этого, есть ли способ получить представления или я должен конструировать свои диалоги по-другому?
Java и трассировка стека ниже:
// Set up the on click of the Button
Button add = (Button) findViewById(R.id.manage_connections_add_button);
add.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(ManageConnectedServicesActivity.this);
builder.setTitle("Add Service");
builder.setView(R.layout.component_sharing_service_dialogue);
// Set up the buttons on the dialog
builder.setPositiveButton("Add", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialogInterface, int i) {
// Get the connected service url
EditText url = (EditText) findViewById(R.id.add_sharing_service_url); // This is the offending line
addConnectedService(url.getText().toString()); // Crashes here
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
builder.show();
}
});
Трассировки стека:
12-05 09:54:40.825 1889-1889/uk.mrshll.matt.accountabilityscrapbook E/AndroidRuntime: FATAL EXCEPTION: main
Process: uk.mrshll.matt.accountabilityscrapbook, PID: 1889
java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
at uk.mrshll.matt.accountabilityscrapbook.ManageConnectedServicesActivity$1$1.onClick(ManageConnectedServicesActivity.java:63)
at android.support.v7.app.AlertController$ButtonHandler.handleMessage(AlertController.java:157)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5343)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:905)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700)
4 ответа
Создайте одно представление для раздувания XML-файла и используйте это представление перед findViewById()
final View view = inflater.inflate(R.layout.schedule,null);
builder.setView(view);
final EditText edtSelectDate = (EditText) view.findViewById(R.id.edtSelectDate);
Используйте этот код, я думаю, что он соответствует вашим требованиям, которые вы хотите
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getContext());
LayoutInflater inflater = getActivity().getLayoutInflater();
View dialogView = inflater.inflate(R.layout.new_post_dialog_layout, null);
dialogBuilder.setView(dialogView);
final EditText editText = (EditText) dialogView.findViewById(R.id.et_question_msg);
Label create = (Label) dialogView.findViewById(R.id.tv_create);
Label cancel = (Label) dialogView.findViewById(R.id.tv_cancel);
final AlertDialog alertDialog = dialogBuilder.create();
alertDialog.setCancelable(false);
alertDialog.setCanceledOnTouchOutside(false);
alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
alertDialog.show();
create.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String ques = editText.getText().toString().trim();
if (TextUtils.isEmpty(ques)) {
Toast.makeText(getContext(), "Enter your question", Toast.LENGTH_SHORT).show();
return;
} else {
//hit your api here
writeNewPost(userId, username, ques);
alertDialog.dismiss();
}
}
});
cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
alertDialog.dismiss();
}
});
myTv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View dialogView = inflater.inflate(R.layout.dialog_forgot_password, null);**
dialogBuilder.setCancelable(true);
final EditText mobileEt;
Button done;
mobileEt = (EditText) dialogView.findViewById(R.id.mobile_et);
done = (Button) dialogView.findViewById(R.id.done);
dialogBuilder.setView(dialogView);
final AlertDialog alertDialog = dialogBuilder.create();
alertDialog.show();
done.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mobileEt.getText().toString().isEmpty()) {
mobileEt.setError(getString(R.string.email_or_mobile));
} else {
alertDialog.dismiss();
hitdApi(mobileEt.getText().toString());
}
);
mobileEt .setText("Please fill the value");
});
}
});
}
Проверьте этот код, как накачать пользовательский диалог с текстом редактирования.
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.custom_dialog, null);
dialogBuilder.setView(dialogView);
final EditText edt = (EditText) dialogView.findViewById(R.id.edit1);
dialogBuilder.setTitle("Custom dialog");
dialogBuilder.setMessage("Enter text below");
dialogBuilder.setPositiveButton("Done", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//do something with edt.getText().toString();
}
});
dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//pass
}
});
AlertDialog b = dialogBuilder.create();
b.show();
Надеюсь, это поможет. Удачного кодирования. Голосуйте за ответ, если вы найдете его полезным