Android在弹出的Activity上显示AlertDialog

时间:2017-08-25 22:11:38

标签: android dialog alertdialog

我正在尝试从弹出的Activity中添加一个AlertDialog弹出窗口(这是一个在Manifest中使用android:theme="@android:style/Theme.Dialog"扩展Activity的Activity。我正在使用:

Context context = getApplicationContext();
LinearLayout layout = new LinearLayout(context);
layout.setOrientation(LinearLayout.VERTICAL);
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Add Extra");
final EditText base = new EditText(builder.getContext());
final EditText value = new EditText(builder.getContext());
base.setHint("Name");
value.setHint("Value");
// Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
base.setInputType(InputType.TYPE_CLASS_TEXT);
value.setInputType(InputType.TYPE_CLASS_TEXT);
layout.addView(base);
layout.addView(value);
builder.setView(layout);
builder.setMessage("")
.setPositiveButton("Save", new DialogInterface.OnClickListener() {
       public void onClick(DialogInterface dialog, int id) {

       }
       })
       .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
       public void onClick(DialogInterface dialog, int id) {
          // User cancelled the dialog
       }
       });
 // Create the AlertDialog object and return it
AlertDialog dialog = builder.create();
dialog.show();

创建我的警报,但我收到一个关于没有正确上下文的错误。是否有特定的方法来获取弹出对话框的上下文?

3 个答案:

答案 0 :(得分:1)

您正在使用getApplicationContext(),而是使用Activity上下文

使用此代替以避免错误

Context context = YourCurrentActivity.this;

答案 1 :(得分:0)

您应该使用活动上下文。

更改此行,

Context context = getApplicationContext();

到此:

Context context = this;

答案 2 :(得分:0)

Android AlertDialog in Activity Dialog.Theme

我再次问了这个问题,其他人遇到这个问题就得到了解答。