如何在对话框中创建一个编辑文本框


211

我正在尝试在用于输入密码的对话框中创建一个edittext框。当我做的时候我做不到。我是初学者。请帮助我。

public class MainActivity extends Activity {

Button create, show, setting;
//String pass="admin";String password;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    create = (Button)findViewById(R.id.amcreate);
    setting = (Button)findViewById(R.id.amsetting);
    show = (Button)findViewById(R.id.amshow);
    //input = (EditText)findViewById(R.id.this);

    setting.setVisibility(View.INVISIBLE);

    create.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            Intent myIntent1 = new Intent(view.getContext(), Create.class);
            startActivityForResult(myIntent1, 0);
        }

    });

    show.setOnClickListener(new View.OnClickListener() {
        //@SuppressWarnings("deprecation")
        public void onClick(final View view) {

            // Creating alert Dialog with one Button
            AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);

            //AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();

            // Setting Dialog Title
            alertDialog.setTitle("PASSWORD");

            // Setting Dialog Message
            alertDialog.setMessage("Enter Password");
            **final EditText input = new EditText(this);**
            //alertDialog.setView(input);

            // Setting Icon to Dialog
            alertDialog.setIcon(R.drawable.key);

            // Setting Positive "Yes" Button
            alertDialog.setPositiveButton("YES",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,int which) {
                            // Write your code here to execute after dialog
                            Toast.makeText(getApplicationContext(),"Password Matched", Toast.LENGTH_SHORT).show();
                            Intent myIntent1 = new Intent(view.getContext(), Show.class);
                            startActivityForResult(myIntent1, 0);
                        }
                    });
            // Setting Negative "NO" Button
            alertDialog.setNegativeButton("NO",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            // Write your code here to execute after dialog
                            dialog.cancel();
                        }
                    });

            // closed

            // Showing Alert Message
            alertDialog.show();
        }

    }); 

图片

在此处输入图片说明

我想得到

在此处输入图片说明

 AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
 alertDialog.setTitle("PASSWORD");
 alertDialog.setMessage("Enter Password");

 final EditText input = new EditText(MainActivity.this);
 LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
     LinearLayout.LayoutParams.MATCH_PARENT,
     LinearLayout.LayoutParams.MATCH_PARENT);
 input.setLayoutParams(lp);
 alertDialog.setView(input);
 alertDialog.setIcon(R.drawable.key);

 alertDialog.setPositiveButton("YES",
     new DialogInterface.OnClickListener() {
         public void onClick(DialogInterface dialog, int which) {
             password = input.getText().toString();
             if (password.compareTo("") == 0) {
                 if (pass.equals(password)) {
                     Toast.makeText(getApplicationContext(),
                         "Password Matched", Toast.LENGTH_SHORT).show();
                     Intent myIntent1 = new Intent(view.getContext(),
                         Show.class);
                     startActivityForResult(myIntent1, 0);
                 } else {
                     Toast.makeText(getApplicationContext(),
                         "Wrong Password!", Toast.LENGTH_SHORT).show();
                 }
             }
         }
     });

 alertDialog.setNegativeButton("NO",
     new DialogInterface.OnClickListener() {
         public void onClick(DialogInterface dialog, int which) {
             dialog.cancel();
         }
     });

 alertDialog.show();
 }

 });

1
检查此developer.android.com/guide/topics/ui/notifiers/toasts.html。检查定位吐司。但是我想最好为edittext设置seterror
Raghunandan

Answers:


171

使用活动上下文

取代这个

  final EditText input = new EditText(this);

通过

  final EditText input = new EditText(MainActivity.this);  
  LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.MATCH_PARENT,
                        LinearLayout.LayoutParams.MATCH_PARENT);
  input.setLayoutParams(lp);
  alertDialog.setView(input); // uncomment this line

1
@Abhishek就是您的初始化。像Dialog dialog = new Dialog(MainActivity.this)。我想您是从其他地方复制了您的代码的
Raghunandan

1
@Abhishek很抱歉让您有自定义对话框的困惑。public void onClick(DialogInterface dialog它的对话框界面。使用那不是问题,您单击否定按钮可以关闭警报对话框。
Raghunandan

1
@Abhishek显示祝酒消息或为edittext设置错误。stackoverflow.com/questions/7747268/…–
Raghunandan

1
Toast toast = Toast.makeText(MainActivity.this,“请输入密码!”,Toast.LENGTH_LONG); toast.setGravity(Gravity.CENTER,0,0); toast.show(); 这对我起作用,使吐司居中。
2013年

5
嗨,Raghu,如果我想在此edittext框中输入左边距和右边距,那我应该写些什么?我尝试了许多答案,以编程方式设置了边距,但是没有任何效果:(
路西法2014年

287

我知道回答这个问题为时已晚,但是对于其他正在搜索与此类似内容的人来说,这是一个带有edittext的警报框的简单代码

AlertDialog.Builder alert = new AlertDialog.Builder(this); 

要么

new AlertDialog.Builder(mContext, R.style.MyCustomDialogTheme);

如果要更改对话框的主题。

final EditText edittext = new EditText(ActivityContext);
alert.setMessage("Enter Your Message");
alert.setTitle("Enter Your Title");

alert.setView(edittext);

alert.setPositiveButton("Yes Option", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
        //What ever you want to do with the value
        Editable YouEditTextValue = edittext.getText();
        //OR
        String YouEditTextValue = edittext.getText().toString();
    }
});

alert.setNegativeButton("No Option", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
        // what ever you want to do with No option.
    }
});

alert.show();

我应该在哪里放置此代码?当我在方法中尝试此操作并将最终字段EditText放在类顶部时,它崩溃。
cerbin

什么是车祸?
Syeda Zunaira

10
如何给此EditText提供空白?
Ghanshyam Nayma '18

1
很好地建议了所询问的主题,但是需要样式注释。Android不是Windows,也不需要取消按钮,就像Win32中的必选按钮一样,操作系统的“后退”按钮用作“取消/否”。因此,我的建议是跳过密码请求对话框上的否定按钮,肯定的按钮不应为“是”,而应为“确定”(并使用android.R.string.ok将其本地化)。请参阅我在stackoverflow.com/questions/11459827/…主题上的答案中的更多内容。
JanBergström18年

2
在密码请求中(因为是这样),编辑字段也应该是一个衬里(edittext.setSingleLine();),并且可以在连接的物理(BT)键盘(或Chromebook)上按Enter键,从而将焦点跳转到下一项,肯定按钮。表示输入文字后,按两次Enter键即可结束对话。
JanBergström18年

36

最简单的就是。

  • 为对话框创建xml布局文件。添加任何想要的视图,例如EditText,ListView,Spinner等。

    膨胀该视图并将其设置为AlertDialog

让我们先从布局文件开始。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:orientation="vertical">


    <EditText
        android:id="@+id/etComments"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="top"
        android:hint="Enter comments(Optional)"
        android:inputType="textMultiLine"
        android:lines="8"
        android:maxLines="3"
        android:minLines="6"
        android:scrollbars="vertical" />

</LinearLayout>

final View view = layoutInflater.inflate(R.layout.xml_file_created_above, null);
AlertDialog alertDialog = new AlertDialog.Builder(ct).create();
alertDialog.setTitle("Your Title Here");
alertDialog.setIcon("Icon id here");
alertDialog.setCancelable(false);
Constant.alertDialog.setMessage("Your Message Here");


final EditText etComments = (EditText) view.findViewById(R.id.etComments);

alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {

    }
});


alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "Cancel", new OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        alertDialog.dismiss()
    }
});


alertDialog.setView(view);
alertDialog.show();

3
你真是英雄。
AdamMcquiff

我崩溃了 我发现崩溃的原因是我错过了findViewById上的“视图”。现在,我只需要知道如何处理复选框,就可以在对话框仍然存在时显示或隐藏密码。尝试了多项目方法,但除了我的布局中的复选框之外,它还添加了自己的复选框!
布赖恩·莱因霍尔德'18

23

简化版

final EditText taskEditText = new EditText(this);
AlertDialog dialog = new AlertDialog.Builder(this)
        .setTitle("Add a new task")
        .setMessage("What do you want to do next?")
        .setView(taskEditText)
        .setPositiveButton("Add", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String task = String.valueOf(taskEditText.getText());
                SQLiteDatabase db = mHelper.getWritableDatabase();
                ContentValues values = new ContentValues();
                values.put(TaskContract.TaskEntry.COL_TASK_TITLE, task);
                db.insertWithOnConflict(TaskContract.TaskEntry.TABLE,
                        null,
                        values,
                        SQLiteDatabase.CONFLICT_REPLACE);
                db.close();
                updateUI();
            }
        })
        .setNegativeButton("Cancel", null)
        .create();
dialog.show();
return true;

12

试试下面的代码:

alert.setTitle(R.string.WtsOnYourMind);

 final EditText input = new EditText(context);
 input.setHeight(100);
 input.setWidth(340);
 input.setGravity(Gravity.LEFT);

 input.setImeOptions(EditorInfo.IME_ACTION_DONE);
 alert.setView(input);

5

在布局参数中设置边距在Alertdialog中不起作用。您必须在父版式中设置填充,然后在该版式中添加edittext。

这是我的工作kotlin代码...

val alert =  AlertDialog.Builder(context!!)

val edittext = EditText(context!!)
edittext.hint = "Enter Name"
edittext.maxLines = 1

val layout = FrameLayout(context!!)

//set padding in parent layout
layout.setPaddingRelative(45,15,45,0)

alert.setTitle(title)

layout.addView(edittext)

alert.setView(layout)

alert.setPositiveButton(getString(R.string.label_save), DialogInterface.OnClickListener {

    dialog, which ->
    run {

        val qName = edittext.text.toString()

        Utility.hideKeyboard(context!!, dialogView!!)

    }

})
alert.setNegativeButton(getString(R.string.label_cancel), DialogInterface.OnClickListener {

            dialog, which ->
            run {
                dismiss()
            }

})

alert.show()

4

您还可以通过创建xml文件来创建自定义警报对话框。

dialoglayout.xml

   <EditText
    android:id="@+id/dialog_txt_name"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_margin="10dp"
    android:hint="Name"
    android:singleLine="true" >

    <requestFocus />
  </EditText>
   <Button
        android:id="@+id/btn_login"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="60dp"
        android:background="@drawable/red"
        android:padding="5dp"
        android:textColor="#ffffff"
        android:text="Submit" />

    <Button
        android:id="@+id/btn_cancel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_toRightOf="@+id/btn_login"
        android:background="@drawable/grey"
        android:padding="5dp"
        android:text="Cancel" />

Java代码:

@Override//to popup alert dialog
public void onClick(View arg0) {
    // TODO Auto-generated method stub
    showDialog(DIALOG_LOGIN);
});


@Override
protected Dialog onCreateDialog(int id) {
    AlertDialog dialogDetails = null;

    switch (id) {
        case DIALOG_LOGIN:
            LayoutInflater inflater = LayoutInflater.from(this);
            View dialogview = inflater.inflate(R.layout.dialoglayout, null);
            AlertDialog.Builder dialogbuilder = new AlertDialog.Builder(this);
            dialogbuilder.setTitle("Title");
            dialogbuilder.setView(dialogview);
            dialogDetails = dialogbuilder.create();
            break;
    }
    return dialogDetails;
}

@Override
protected void onPrepareDialog(int id, Dialog dialog) {
    switch (id) {
        case DIALOG_LOGIN:
             final AlertDialog alertDialog = (AlertDialog) dialog;
             Button loginbutton = (Button) alertDialog
                .findViewById(R.id.btn_login);
             Button cancelbutton = (Button) alertDialog
                .findViewById(R.id.btn_cancel);
             userName = (EditText) alertDialog
                .findViewById(R.id.dialog_txt_name);
             loginbutton.setOnClickListener(new View.OnClickListener() {
                  @Override
                  public void onClick(View v) {
                      String name = userName.getText().toString();
                      Toast.makeText(Activity.this, name,Toast.LENGTH_SHORT).show();
             });
             cancelbutton.setOnClickListener(new View.OnClickListener() {
                      @Override
                      public void onClick(View v) {
                           alertDialog.dismiss();
                      }
             });
             break;
   }
}

这就是我所需要的,但是我该如何使用它来片段化其显示的错误
Raju

0

Wasim的答案将我引向正确的方向,但我必须进行一些更改才能使其在当前项目中正常工作。我在一个片段中使用此函数,并在单击按钮时调用它。

fun showPostDialog(title: String) {
        val alert =  AlertDialog.Builder(activity)

        val edittext = EditText(activity)
        edittext.hint = "Enter Name"
        edittext.maxLines = 1

        var layout = activity?.let { FrameLayout(it) }

        //set padding in parent layout
//        layout.isPaddingRelative(45,15,45,0)
        layout?.setPadding(45,15,45,0)

        alert.setTitle(title)

        layout?.addView(edittext)

        alert.setView(layout)

        alert.setPositiveButton(getString(R.string.label_save), DialogInterface.OnClickListener {

                dialog, which ->
            run {

                val qName = edittext.text.toString()

                showToast("Posted to leaderboard successfully")

                view?.hideKeyboard()

            }

        })
        alert.setNegativeButton(getString(R.string.label_cancel), DialogInterface.OnClickListener {

                dialog, which ->
            run {
                dialog.dismiss()
            }

        })

        alert.show()
    }

    fun View.hideKeyboard() {
        val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(windowToken, 0)
    }

    fun showToast(message: String) {
        Toast.makeText(activity, message, Toast.LENGTH_LONG).show()
    }

我希望它会在不久的将来对其他人有所帮助。编码愉快!

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.