programing

대화 상자에서 편집 텍스트 상자를 만드는 방법

topblog 2023. 8. 6. 09:06
반응형

대화 상자에서 편집 텍스트 상자를 만드는 방법

비밀번호를 입력하기 위한 대화상자에서 편집 텍스트 상자를 만들려고 하는데 입력할 수 없습니다.저는 그것에 초보자입니다.이 일을 도와주세요.

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();
        }

    }); 

이미지

enter image description here

저는 다음과 같이 받고 싶습니다.

enter image description here

 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();
 }

 });

이 질문에 대답하기에는 너무 늦었다는 것을 알지만, 이와 유사한 것을 검색하는 다른 사람들을 위해 여기 편집 텍스트가 있는 알림 상자의 간단한 코드가 있습니다.

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();

활동 컨텍스트 사용

바꾸기

  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

가장 간단한 것은.

  • 대화 상자의 xml 레이아웃 파일을 만듭니다.텍스트 편집, 목록 보기, 스피너 등 원하는 보기를 추가합니다.

    이 보기를 부풀리고 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(requireContext()).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();

단순화된 버전

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;

아래 코드를 사용해 보십시오.

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);

레이아웃 파라미터의 여백 설정은 Alert(경고) 대화상자에서 작동하지 않습니다.부모 레이아웃에 패딩을 설정한 다음 해당 레이아웃에 편집 텍스트를 추가해야 합니다.

이건 내 코틀린 코드야

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()

xml 파일을 만들어 사용자 지정 경고 대화 상자를 만들 수도 있습니다.

대화상자 layout.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;
   }
}

와심의 대답은 저를 올바른 방향으로 이끌었지만, 저는 그것이 현재의 프로젝트에서 작동하도록 하기 위해 약간의 변화를 주어야 했습니다.나는 이 기능을 fragment에서 사용하고 있고 버튼 클릭으로 호출하고 있습니다.

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()
    }

가까운 미래에 다른 누군가에게 도움이 되길 바랍니다.해피 코딩!

아래 코드로 시도할 수 있습니다.

I created a Method like this

 public void getReferDialog(OnSubmitBtnClick submitBtnClick) {
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(activity);
    final View customLayout = activity.getLayoutInflater().inflate(R.layout.dilog_refer_id, null);
    alertDialog.setView(customLayout);
    AlertDialog alert = alertDialog.create();
    alert.setCancelable(false);
    alert.setCanceledOnTouchOutside(false);
    EditText editText = customLayout.findViewById(R.id.ed_refer_user_input);
    Button submitBtn = customLayout.findViewById(R.id.btn_refer_submit);
    TextView tvNo = customLayout.findViewById(R.id.tv_no_thanks);
    TextView tvBody = customLayout.findViewById(R.id.tv_title_refer_dialog_body);

    submitBtn.setOnClickListener(v -> {
        String userText = editText.getText().toString();
        if (!userText.equals("")) {
            alert.dismiss();
            submitBtnClick.onClick(userText);
        }else {
            tvBody.setTextColor(Color.RED);
        }
    });

    tvNo.setOnClickListener(v -> {
        alert.dismiss();
        submitBtnClick.onClick("skip");
    });
    alert.show();
}

Here is my dilog_refer_id.xml file

 <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/white"
    android:paddingTop="24dp"
    android:paddingStart="24dp"
    android:paddingEnd="24dp"
    android:paddingBottom="14dp">

    <TextView
        android:id="@+id/tv_title_refer_dialog_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="10dp"
        android:fontFamily="@font/segoe_ui_bold"
        android:gravity="start"
        android:text="@string/refer_by_dialog_title"
        android:textColor="@color/colorPrimary"
        android:textSize="18sp" />

    <TextView
        android:id="@+id/tv_title_refer_dialog_body"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/tv_title_refer_dialog_title"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="10dp"
        android:fontFamily="@font/segoe_ui_regular"
        android:gravity="start"
        android:text="@string/refer_by_dialog_body"
        android:textColor="@color/colorPrimary"
        android:textSize="14sp" />

    <EditText
        android:id="@+id/ed_refer_user_input"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/tv_title_refer_dialog_body"
        android:layout_marginTop="10dp"
        android:autofillHints="FDCT4G"
        android:background="@drawable/bg_edit_text_refer"
        android:fontFamily="@font/seg_ui_semibold"
        android:hint="@string/dialog_refer_by"
        android:inputType="textCapCharacters"
        android:minHeight="48dp"
        android:padding="10dp"
        android:textColor="@color/colorPrimary"
        android:textColorHint="@color/colorPrimary"
        android:textSize="14sp" />

    <Button
        android:id="@+id/btn_refer_submit"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:layout_below="@+id/ed_refer_user_input"
        android:layout_centerHorizontal="true"
        android:layout_margin="16dp"
        android:background="@drawable/btn_bg"
        android:text="@string/submit"
        android:textColor="@color/textPrimaryColor" />

    <TextView
        android:id="@+id/tv_no_thanks"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/btn_refer_submit"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="10dp"
        android:fontFamily="@font/segoe_ui_bold"
        android:gravity="center"
        android:text="@string/skip"
        android:padding="10dp"
        android:textColor="@color/drawer_item"
        android:textSize="14sp" />
</RelativeLayout>

My bg_edit_text_refer.xml(drawable) file

    <?xml version="1.0" encoding="utf-8"?>
<shape android:shape="rectangle" xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@color/home_bg_extension"/>
    <corners android:radius="15dp"/>
</shape>

Creating a Interface for get user input data

public interface OnSubmitBtnClick {
    void onClick(String referId);
}

Finally all done now time to call it onclick method

showPopupBtn.setOnClickListener(v -> {
        getReferDialog(new OnSubmitBtnClick() {
            @Override
            public void onClick(String referId) {
                Toast.makeText(LoginActivity.this, referId, Toast.LENGTH_SHORT).show();
            }
        });
    });

감사합니다, 해피 코딩!!

언급URL : https://stackoverflow.com/questions/18799216/how-to-make-a-edittext-box-in-a-dialog

반응형