대화 네거티브 포지티브 버튼을 비활성화 / 활성화하는 방법은 무엇입니까?
아래의 사용자 정의 대화 상자를보십시오. 대화 상자에 edittext 필드가 있고 텍스트 필드가 비어 있으면 positiveButton
. 텍스트 필드에 대한 charListener를 얻을 수 있지만 positivebutton
해당 수신기에서 비활성화 또는 활성화 하도록 설정하는 방법을 잘 모르겠습니다 . 포지티브 및 네거티브 버튼에 대한 참조는 무엇입니까?
case DIALOG_TEXT_ENTRY:
// This example shows how to add a custom layout to an AlertDialog
LayoutInflater factory = LayoutInflater.from(this);
final View textEntryView = factory.inflate(R.layout.alert_dialog_text_entry, null);
return new AlertDialog.Builder(AlertDialogSamples.this)
.setIconAttribute(android.R.attr.alertDialogIcon)
.setTitle(R.string.alert_dialog_text_entry)
.setView(textEntryView)
.setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* User clicked OK so do some stuff */
}
})
.setNegativeButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* User clicked cancel so do some stuff */
}
})
.create();
}
완전한 솔루션 편집 ...
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setIcon(android.R.drawable.ic_dialog_info);
builder.setTitle("Alert dialog title");
builder.setMessage("This is the example code snippet to disable button if edittext attached to dialog is empty.");
builder.setPositiveButton("PositiveButton",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
// DO TASK
}
});
builder.setNegativeButton("NegativeButton",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
// DO TASK
}
});
// Set `EditText` to `dialog`. You can add `EditText` from `xml` too.
final EditText input = new EditText(MainActivity.this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT
);
input.setLayoutParams(lp);
builder.setView(input);
final AlertDialog dialog = builder.create();
dialog.show();
// Initially disable the button
((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
// OR you can use here setOnShowListener to disable button at first time.
// Now set the textchange listener for edittext
input.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void afterTextChanged(Editable s) {
// Check if edittext is empty
if (TextUtils.isEmpty(s)) {
// Disable ok button
((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
} else {
// Something into edit text. Enable the button.
((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(true);
}
}
});
아래는 편집 된 내역이며 자세한 내용은 참조 할 수 있습니다.
다음은 샘플 코드입니다.
AlertDialog.Builder builder = new AlertDialog.Builder(AddSchedule.this);
builder.setIcon(android.R.drawable.ic_dialog_info);
builder.setTitle("Alert dialog title");
builder.setMessage("Dialog message");
builder.setPositiveButton("Button1", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
//DO TASK
}
});
builder.setNegativeButton("Button2", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
//DO TASK
}
});
AlertDialog dialog = builder.create();
dialog.show();
// After calling show method, you need to check your condition and enable/disable the dialog buttons
if (your_condition_true) {
// BUTTON1 is the positive button
dialog.getButton(AlertDialog.BUTTON1).setEnabled(false);
}
네거티브 버튼
dialog.getButton(AlertDialog.BUTTON2).setEnabled(false); //BUTTON2 is negative button
버튼 ID의 경우 : alert_dialog.xml 참조
편집 :
그리고 레벨 8 API (FroYo) 이후 의 setOnShowListener 는 동일한 작업을 수행합니다.
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.setOnShowListener(new OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
if (condition) {
((AlertDialog)dialog).getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
}
}
});
dialog.show();
편집
new AlertDialog.Builder(this)
.setMessage("This may take a while")
.setPositiveButton("OK", new android.content.DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
((AlertDialog)dialog).getButton(which).setVisibility(View.INVISIBLE);
// the rest of your stuff
}
}).show();
이 답변 중 어느 것도 문제를 실제로 해결하지 못합니다.
EditText가있는 사용자 지정 레이아웃과 해당 뷰의 TextWatcher를 사용하여이를 수행합니다.
final LinearLayout layout = (LinearLayout) inflator.inflate(R.layout.text_dialog, null);
final EditText text = (EditText) layout.findViewById(R.id.text_edit);
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(layout);
// Now add the buttons...
builder.setPositiveButton(R.string.ok, new AlertDialog.OnClickListener() {
// Left out for brevity...
}
builder.setNegativeButton(R.string.cancel, new AlertDialog.OnClickListener() {
// Left out for brevity...
}
// Create the dialog
final AlertDialog d = builder.create();
// Now add a TextWatcher that will handle enable/disable of save button
text.addTextChangedListener(new TextWatcher() {
private void handleText() {
// Grab the button
final Button okButton = d.getButton(AlertDialog.BUTTON_POSITIVE);
if(text.getText().length() == 0) {
okButton.setEnabled(false);
} else {
okButton.setEnabled(true);
}
}
@Override
public void afterTextChanged(Editable arg0) {
handleText();
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// Nothing to do
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// Nothing to do
}
});
// show the dialog
d.show();
// and disable the button to start with
d.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
다음은 대화 상자의 긍정적 버튼을 활성화 및 비활성화하는 완전한 코드입니다.
AlertDialog.Builder builder = new AlertDialog.Builder(this);
LayoutInflater layoutInflater = MainActivity.this.getLayoutInflater();
View view = layoutInflater.inflate(R.layout.dialog,null);
builder.setView(view);
builder.setTitle("Test");
builder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "Ok clicked", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
builder.setNegativeButton("cancel", null);
final AlertDialog alertDialog = builder.create();
alertDialog.show();
EditText editText = (EditText)view.findViewById(R.id.mobile_number);
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
if(s.length()>=1)
{
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(true);
}
else {
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
}
}
});
뷰 홀더를 사용하여 데이터베이스 목록보기에서 레코드를 삭제하려면 getview () 메서드에서이 코드를 사용했습니다.
viewHolder.btn.setOnClickListener (new OnClickListener () {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
AlertDialog.Builder alertDialog2 = new AlertDialog.Builder(
Favorate.this.getParent());
// Setting Dialog Title
alertDialog2.setTitle("Confirm Delete...");
// Setting Dialog Message
alertDialog2
.setMessage("Are you sure you want delete ?");
// Setting Icon to Dialog
alertDialog2.setIcon(R.drawable.delete);
// Setting Positive "Yes" Btn
alertDialog2.setPositiveButton("YES",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
// Write your code here to execute after
// dialog
int id = _items.get(position).id;
db.deleterecord(id);
db.close();
}
});
// Setting Negative "NO" Btn
alertDialog2.setNegativeButton("NO",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
// Write your code here to execute after
// dialog
dialog.cancel();
}
});
// Showing Alert Dialog
alertDialog2.show();
}
});
이 dialogFragment는 당신을 위해 일을 할 것입니다. 대화 상자는 사용자가 이미 입력 한 모든 텍스트를 유지하면서 화면 회전 후에도 열린 상태로 유지됩니다. 이런 일이 발생하지 않도록하려면 활동의 onStop에서 조각을 닫아야합니다. newInstance 메소드 서명은 필요한대로 변경할 수 있습니다.
import android.app.Activity;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
public class TextViewDialogFragment extends DialogFragment implements DialogInterface.OnClickListener, DialogInterface.OnShowListener, TextWatcher
{
final static private String TITLE = "title", MESSAGE = "message", IDENTIFIER = "identifier", INPUT_TYPE = "inputType", POSITIVE_TEXT = "pText", NEGATIVE_TEXT = "nText", CANCELABLE = "cancelable";
public TextViewDialogFragment()
{
super();
}
static public TextViewDialogFragment newInstance(int title, @Nullable String message, int identifier, int inputType, int positiveText, int negativeText, boolean cancelable)
{
TextViewDialogFragment fragement = new TextViewDialogFragment();
Bundle args = new Bundle();
args.putInt(TITLE, title);
args.putString(MESSAGE, message);
args.putInt(IDENTIFIER, identifier);
args.putInt(INPUT_TYPE, inputType);
args.putInt(POSITIVE_TEXT, positiveText);
args.putInt(NEGATIVE_TEXT, negativeText);
args.putBoolean(CANCELABLE, cancelable);
fragement.setArguments(args);
return fragement;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
Activity activity = getActivity();
Bundle args = getArguments();
EditText input = new EditText(activity);
input.setInputType(args.getInt(INPUT_TYPE));
input.setId(R.id.dialog_edit_text);
input.addTextChangedListener(this);
AlertDialog.Builder alert = new AlertDialog.Builder(activity);
alert.setCancelable(args.getBoolean(CANCELABLE)).setTitle(args.getInt(TITLE)).setMessage(args.getString(MESSAGE)).setView(input).setPositiveButton(args.getInt(POSITIVE_TEXT), this);
int negativeText = args.getInt(NEGATIVE_TEXT);
if (negativeText != 0)
{
alert.setNegativeButton(negativeText, this);
}
AlertDialog dialog = alert.create();
dialog.setOnShowListener(this);
return dialog;
}
@Override
public void onShow(DialogInterface dialog)
{
// After device rotation there may be some text present.
if (((EditText)((AlertDialog) dialog).findViewById(R.id.dialog_edit_text)).length() == 0)
{
((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
}
}
@Override
public void onClick(DialogInterface dialog, int which)
{
String text = ((EditText)((AlertDialog) dialog).findViewById(R.id.dialog_edit_text)).getText().toString();
((Callbacks) getActivity()).onTextViewDialogResult(which, getArguments().getInt(IDENTIFIER), text);
}
@Override
public void onCancel(DialogInterface dialog)
{
((Callbacks) getActivity()).onTextViewDialogActivityCancelled(getArguments().getInt(IDENTIFIER));
super.onCancel(dialog);
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
}
@Override
public void afterTextChanged(Editable s)
{
((AlertDialog) getDialog()).getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(s.length() > 0);
}
void setMessage(String message)
{
Bundle args = getArguments();
args.putString(MESSAGE, message);
setArguments(args);
}
interface Callbacks
{
void onTextViewDialogResult(int which, int identity, String text);
void onTextViewDialogActivityCancelled(int identity);
}
}
활동에 구현을 추가하십시오 (모든 유형의 활동이 좋습니다).
public class Myctivity extends AppCompatActivity implements TextViewDialogFragment.Callbacks
{
...
}
다음과 같이 활동에서 diaglogFragment를 만듭니다.
final static int SOMETHING = 1;
myDF = TextViewDialogFragment.newInstance(R.string.my_title, "my message", SOMETHING, InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_WORDS | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, /* Whatever is best for your user. */ R.string.yay, android.R.string.cancel, true);
다음과 같이 활동의 결과를 처리하십시오.
@Override
public void onTextViewDialogResult(int which, int identity, String text)
{
if (which == AlertDialog.BUTTON_NEGATIVE)
{
// User did not want to do anything.
return;
}
// text now holds the users answer.
// Identity can be used if you use the same fragment for more than one type of question.
}
@Override
public void onTextViewDialogActivityCancelled(int identity)
{
// This is invoked if you set cancelable to true and the user pressed the back button.
}
리소스 식별자를 만들어야하므로 res / values 아래 어딘가에이 리소스를 추가해야합니다.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item name="dialog_edit_text" type="id"/>
</resources>
if(editTextEmailAddress.getText().toString().length()==0)
{
btnCancelCross.setEnabled(false);
}
else
{
btnCancelCross.setEnabled(true);
}
감사합니다.
참고 URL : https://stackoverflow.com/questions/8238952/how-to-disable-enable-dialog-negative-positive-buttons
'IT박스' 카테고리의 다른 글
JSON 객체에 새 배열 요소 추가 (0) | 2020.08.07 |
---|---|
setTimeout은 Node.JS에서 어떻게 작동합니까? (0) | 2020.08.07 |
Java에서 정수의 0 패딩 이진 표현을 얻는 방법은 무엇입니까? (0) | 2020.08.07 |
mongodb가 실행 중입니까? (0) | 2020.08.07 |
Javascript-파일 입력 컨트롤에서 파일 이름을 추출하는 방법 (0) | 2020.08.06 |