2

我第一次使用 Android Preferences 并遇到了意想不到的问题。

我正在扩展 DialogPreference 类,除了一件事外,所有工作都很好:在方法 onDialogClosing(boolean positiveResult) 中,无论我按下什么按钮,我都收到错误消息。我做错了什么?

该类的完整代码如下所示。

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

}
4

1 回答 1

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);
        }
}
于 2013-12-28T06:14:32.937 回答