2013-09-23 54 views
2

我第一次使用Android偏好設置並遇到意外問題。DialogPreference.onDialogClosing(布爾值)總是收到positiveResult == false

我擴展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); 
     } 
}