Android - getDialog не возвращает экземпляр AlertDialog

Я работал над приложением курса Google по поиску солнечного света и хотел, чтобы в него вошел мой личный контакт, поэтому я заставил пользователя указать свой город, используя гибрид EditTextPreference и AutoCompleteTextView, показанный здесь:

public class AutoCompleteEditTextPreference extends EditTextPreference {

private static String[] list;
private boolean isValid = true;
private Dialog dialog;

public AutoCompleteEditTextPreference(Context context) {
    super(context);
}

public AutoCompleteEditTextPreference(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public AutoCompleteEditTextPreference(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
}

/**
 * the default EditTextPreference does not make it easy to
 * use an AutoCompleteEditTextPreference field. By overriding this method
 * we perform surgery on it to use the type of edit field that
 * we want.
 */
protected void onBindDialogView(View view) {
    super.onBindDialogView(view);

    // find the current EditText object
    final EditText editText = (EditText) view.findViewById(android.R.id.edit);
    // copy its layout params
    ViewGroup.LayoutParams params = editText.getLayoutParams();
    ViewGroup vg = (ViewGroup) editText.getParent();
    String curVal = editText.getText().toString();
    // remove it from the existing layout hierarchy
    vg.removeView(editText);

    // construct a new editable autocomplete object with the appropriate params
    // and id that the TextEditPreference is expecting
    mACTV = new AutoCompleteTextView(getContext());
    mACTV.setLayoutParams(params);
    mACTV.setId(android.R.id.edit);
    mACTV.setText(curVal);


    Arrays.sort(list);

    isValid  = isValid(mACTV.getText().toString());


    mACTV.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) {
            isValid = isValid(s.toString());
            validate();
        }
    });

    mACTV.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            isValid = isValid(mACTV.getText().toString());
            validate();
        }
    });

    ArrayAdapter<String> adapter = new ArrayAdapter<>(getContext(),
            android.R.layout.simple_dropdown_item_1line, list);
    mACTV.setAdapter(adapter);

    // add the new view to the layout
    vg.addView(mACTV);
}

private boolean isValid(CharSequence text) {
    return !text.equals("") && Arrays.binarySearch(list, text.toString()) > 0;
}

@Override
protected void showDialog(Bundle state) {
    super.showDialog(state);
    validate();
}

private void validate() {
    dialog = getDialog();
    Toast.makeText(getContext(), Boolean.toString(dialog instanceof AlertDialog), Toast.LENGTH_SHORT).show();

    if (dialog instanceof AlertDialog) {
        Button btn = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE);
        btn.setEnabled(isValid);
    }
}

/**
 * Because the baseclass does not handle this correctly
 * we need to query our injected AutoCompleteTextView for
 * the value to save
 */
protected void onDialogClosed(boolean positiveResult) {
    super.onDialogClosed(positiveResult);

    if (positiveResult && mACTV != null) {

        String value = mACTV.getText().toString();

        if (callChangeListener(value))
            setText(value);
    }
}


static void prepareCountriesList(Context context) {

    List<String> lines = new ArrayList<>();

    try {

        InputStream inputStream = context.getAssets().open("cities.txt");
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

        String line;

        while ((line = bufferedReader.readLine()) != null) {
            lines.add(line);
        }

    } catch (IOException e) {
        e.printStackTrace();
    }

    list = lines.toArray(new String[lines.size()]);
}

/**
 * again we need to override methods from the base class
 */
public EditText getEditText() {
    return mACTV;
}

private AutoCompleteTextView mACTV = null;
private final String TAG = "AutoCompleteEditTextPreference";
}

так что все шло отлично до последней части, где я хотел отключить кнопку ОК

private void validate() {
    dialog = getDialog();
    Toast.makeText(getContext(), Boolean.toString(dialog instanceof AlertDialog), Toast.LENGTH_SHORT).show();

    if (dialog instanceof AlertDialog) {
        Button btn = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE);
        btn.setEnabled(isValid);
    }
}

поэтому я пытаюсь метод getDialog();

и он возвращает диалоговое окно, которое не является нулевым и не является экземпляром AlertDialog

anyhelp, пожалуйста, при получении диалога правильно или другого способа программно отключить кнопку ОК

1 ответ

Решение

Это нормально, нашел проблему; это было то, что я использовал

import android.support.v7.app.AlertDialog;

вместо

import android.app.AlertDialog;

спасибо всем, кто пытался помочь

Другие вопросы по тегам