DialogPreference.onDialogClosing(логическое значение) всегда получает positiveResult == false

Я впервые использую настройки Android и столкнулся с неожиданной проблемой.

Я расширяю класс DialogPreference, и все работает отлично, за исключением одного: в методе onDialogClosing(boolean positiveResult) я получаю false независимо от того, на какую кнопку я нажал. Что я делаю не так?

Весь код класса указан ниже.

package edu.kpi.ept.labwork1;

import android.content.Context;
import android.content.DialogInterface;
import android.content.res.TypedArray;
import android.preference.DialogPreference;
import android.util.AttributeSet;
import android.view.View;
import android.widget.EditText;

public class PositivePickerPreference extends DialogPreference {

private static int DEFAULT_VALUE = 0;

private int selectedValue;
private EditText intEdit;

public PositivePickerPreference(Context context, AttributeSet attrs) {
    super(context, attrs);
    this.setDialogLayoutResource(R.layout.int_pick_pref_dialog);
    this.setPositiveButtonText(R.string.preference_ok);
    this.setNegativeButtonText(R.string.preference_cancel);
}

@Override
protected void onBindDialogView(View view) {
    super.onBindDialogView(view);
    intEdit = (EditText) view.findViewById(R.id.intEdit);
    selectedValue = getPersistedInt(DEFAULT_VALUE);
    intEdit.setText(Integer.toString(selectedValue));
}

public void onClick (DialogInterface dialog, int which) {
    super.onClick();
    selectedValue = Integer.parseInt(intEdit.getText().toString());
}

@Override
protected void onDialogClosed(boolean positiveResult) {
    super.onDialogClosed(positiveResult);
    if (positiveResult) {
        persistInt(selectedValue);
    }
}

@Override
protected void onSetInitialValue(boolean restorePersistedValue, Object defaultValue) {
    super.onSetInitialValue(restorePersistedValue, defaultValue);
    if (restorePersistedValue) {
        selectedValue = getPersistedInt(DEFAULT_VALUE);
    } else {
        selectedValue = (Integer) defaultValue;
        persistInt(selectedValue);

    }
}

@Override
protected Object onGetDefaultValue(TypedArray a, int index) {
    return a.getInteger(index, DEFAULT_VALUE);
}

}

1 ответ

Решение

Просто была такая же проблема. Это из-за обработчика onClick:

public void onClick (DialogInterface dialog, int which) {
    super.onClick();
    selectedValue = Integer.parseInt(intEdit.getText().toString());
}

Удалите его, и у вас не будет проблемы. Если вам нужно знать, какая кнопка нажата, просто проверьте тип кнопки в этом блоке обработчика событий. Например

@Override
public void onClick(DialogInterface dialog, int which) {
    buttonPress = which;
}
@Override
protected void onDialogClosed(boolean positiveResult) {
    super.onDialogClosed(positiveResult);

if (buttonPress == DialogInterface.BUTTON_NEGATIVE) {
            String computerName = _etComputerName.getText().toString();
            SharedPreferences computers = _context.getSharedPreferences(
                    "COMPUTERS", 0);
            SharedPreferences.Editor editor = computers.edit();
            editor.remove(computerName);
            editor.commit();
            this.callChangeListener(-1);
        }
}
Другие вопросы по тегам