경고 대화 상자에 두 개의 편집 텍스트 필드를 추가하는 방법
경고 대화 상자를 사용하여 Android에서 사용자 이름과 암호를 묻는 메시지를 표시하려고합니다. 여기 에서이 코드를 찾았 습니다.
if (token.equals("Not Found"))
{
LayoutInflater factory = LayoutInflater.from(this);
final View textEntryView = factory.inflate(R.layout.userpasslayout, null);
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Please Login to Fogbugz");
alert.setMessage("Enter your email and password");
// Set an EditText view to get user input
alert.setView(textEntryView);
AlertDialog loginPrompt = alert.create();
final EditText input1 = (EditText) loginPrompt.findViewById(R.id.username);
final EditText input2 = (EditText) loginPrompt.findViewById(R.id.password);
alert.setPositiveButton("Login", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
input1.getText().toString(); **THIS CRASHES THE APPLICATION**
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert.show();
}
편집 : 적절한 레이아웃을 설정할 수 있었지만 텍스트 필드에 액세스하려고하면 오류가 발생합니다. 여기서 문제는 무엇입니까?
Android SDK 의 API 데모 에는이를 수행하는 예제가 있습니다.
아래에 DIALOG_TEXT_ENTRY
있습니다. 그들은 레이아웃을 가지고 있고 그것을으로 부풀리고 그것을 LayoutInflater
View로 사용합니다.
편집 : 원래 답변에서 링크 한 것은 부실합니다. 여기에 거울이 있습니다.
알림 상자에서이 코드를 확인하면 확인을 클릭하면 텍스트보기가 편집되어 토스트를 사용하여 화면에 표시됩니다.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final AlertDialog.Builder alert = new AlertDialog.Builder(this);
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String value = input.getText().toString().trim();
Toast.makeText(getApplicationContext(), value,
Toast.LENGTH_SHORT).show();
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
});
alert.show();
}
textEntryView가 사용자 이름 edittext 및 암호 edittext의 부모이므로 코드에서이 줄을 사용합니다.
final EditText input1 = (EditText) textEntryView .findViewById(R.id.username);
final EditText input2 = (EditText) textEntryView .findViewById(R.id.password);
LayoutInflater factory = LayoutInflater.from(this);
final View textEntryView = factory.inflate(R.layout.text_entry, null);
//text_entry is an Layout XML file containing two text field to display in alert dialog
final EditText input1 = (EditText) textEntryView.findViewById(R.id.EditText1);
final EditText input2 = (EditText) textEntryView.findViewById(R.id.EditText2);
input1.setText("DefaultValue", TextView.BufferType.EDITABLE);
input2.setText("DefaultValue", TextView.BufferType.EDITABLE);
final AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setIcon(R.drawable.icon)
.setTitle("Enter the Text:")
.setView(textEntryView)
.setPositiveButton("Save",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Log.i("AlertDialog","TextEntry 1 Entered "+input1.getText().toString());
Log.i("AlertDialog","TextEntry 2 Entered "+input2.getText().toString());
/* User clicked OK so do some stuff */
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
}
});
alert.show();
/* Didn't test it but this should work "out of the box" */
AlertDialog.Builder builder = new AlertDialog.Builder(this);
//you should edit this to fit your needs
builder.setTitle("Double Edit Text");
final EditText one = new EditText(this);
from.setHint("one");//optional
final EditText two = new EditText(this);
to.setHint("two");//optional
//in my example i use TYPE_CLASS_NUMBER for input only numbers
from.setInputType(InputType.TYPE_CLASS_NUMBER);
to.setInputType(InputType.TYPE_CLASS_NUMBER);
LinearLayout lay = new LinearLayout(this);
lay.setOrientation(LinearLayout.VERTICAL);
lay.addView(one);
lay.addView(two);
builder.setView(lay);
// Set up the buttons
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//get the two inputs
int i = Integer.parseInt(one.getText().toString());
int j = Integer.parseInt(two.getText().toString());
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
});
builder.show();
Check the following code. It shows 2 edit text fields programmatically without any layout xml. Change 'this' to 'getActivity()' if you use it in a fragment.
The tricky thing is we have to set the second text field's input type after creating alert dialog, otherwise, the second text field shows texts instead of dots.
public void showInput() {
OnFocusChangeListener onFocusChangeListener = new OnFocusChangeListener() {
@Override
public void onFocusChange(final View v, boolean hasFocus) {
if (hasFocus) {
// Must use message queue to show keyboard
v.post(new Runnable() {
@Override
public void run() {
InputMethodManager inputMethodManager= (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.showSoftInput(v, 0);
}
});
}
}
};
final EditText editTextName = new EditText(this);
editTextName.setHint("Name");
editTextName.setFocusable(true);
editTextName.setClickable(true);
editTextName.setFocusableInTouchMode(true);
editTextName.setSelectAllOnFocus(true);
editTextName.setSingleLine(true);
editTextName.setImeOptions(EditorInfo.IME_ACTION_NEXT);
editTextName.setOnFocusChangeListener(onFocusChangeListener);
final EditText editTextPassword = new EditText(this);
editTextPassword.setHint("Password");
editTextPassword.setFocusable(true);
editTextPassword.setClickable(true);
editTextPassword.setFocusableInTouchMode(true);
editTextPassword.setSelectAllOnFocus(true);
editTextPassword.setSingleLine(true);
editTextPassword.setImeOptions(EditorInfo.IME_ACTION_DONE);
editTextPassword.setOnFocusChangeListener(onFocusChangeListener);
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.addView(editTextName);
linearLayout.addView(editTextPassword);
DialogInterface.OnClickListener alertDialogClickListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case DialogInterface.BUTTON_POSITIVE:
// Done button clicked
break;
case DialogInterface.BUTTON_NEGATIVE:
// Cancel button clicked
break;
}
}
};
final AlertDialog alertDialog = (new AlertDialog.Builder(this)).setMessage("Please enter name and password")
.setView(linearLayout)
.setPositiveButton("Done", alertDialogClickListener)
.setNegativeButton("Cancel", alertDialogClickListener)
.create();
editTextName.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
editTextPassword.requestFocus(); // Press Return to focus next one
return false;
}
});
editTextPassword.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
// Press Return to invoke positive button on alertDialog.
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).performClick();
return false;
}
});
// Must set password mode after creating alert dialog.
editTextPassword.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
editTextPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
alertDialog.show();
}
Have a look at the AlertDialog docs. As it states, to add a custom view to your alert dialog you need to find the frameLayout and add your view to that like so:
FrameLayout fl = (FrameLayout) findViewById(android.R.id.custom);
fl.addView(myView, new LayoutParams(MATCH_PARENT, WRAP_CONTENT));
Most likely you are going to want to create a layout xml file for your view, and inflate it:
LayoutInflater inflater = getLayoutInflater();
View twoEdits = inflater.inflate(R.layout.my_layout, f1, false);
I found another set of examples for customizing an AlertDialog from a guy named Mossila. I think they're better than Google's examples. To quickly see Google's API demos, you must import their demo jar(s) into your project, which you probably don't want.
But Mossila's example code is fully self-contained. It can be directly cut-and-pasted into your project. It just works! Then you only need to tweak it to your needs. See here
ReferenceURL : https://stackoverflow.com/questions/3426917/how-to-add-two-edit-text-fields-in-an-alert-dialog
'Development Tip' 카테고리의 다른 글
Regex.Replace를 사용하여 문자열에서 숫자를 제거하는 방법은 무엇입니까? (0) | 2021.01.10 |
---|---|
표준 API에 자연 비교기가 존재합니까? (0) | 2021.01.10 |
ActionBar의 오버플로 버튼 색상 변경 (0) | 2021.01.10 |
d3.js & nvd3.js — y 축 범위 설정 방법 (0) | 2021.01.10 |
select2 상자 높이를 어떻게 변경합니까? (0) | 2021.01.10 |