2

最初に Android の設定を使用していて、予期しない問題が発生しました。

私は DialogPreference クラスを拡張していますが、1 つのことを除いてすべて正常に動作します: メソッド 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);
}

}
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 に答える