我已经按照上一个答案的建议做了,并基于 Android 源代码实现了我自己的 ListPreference。下面是我添加 OK 按钮的实现。
myPreferenceList.java
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.preference.ListPreference;
import android.util.AttributeSet;
public class myPreferenceList extends ListPreference implements OnClickListener{
private int mClickedDialogEntryIndex;
public myPreferenceList(Context context, AttributeSet attrs) {
super(context, attrs);
}
public myPreferenceList(Context context) {
this(context, null);
}
private int getValueIndex() {
return findIndexOfValue(this.getValue() +"");
}
@Override
protected void onPrepareDialogBuilder(Builder builder) {
super.onPrepareDialogBuilder(builder);
mClickedDialogEntryIndex = getValueIndex();
builder.setSingleChoiceItems(this.getEntries(), mClickedDialogEntryIndex, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
mClickedDialogEntryIndex = which;
}
});
System.out.println(getEntry() + " " + this.getEntries()[0]);
builder.setPositiveButton("OK", this);
}
public void onClick (DialogInterface dialog, int which)
{
this.setValue(this.getEntryValues()[mClickedDialogEntryIndex]+"");
}
}
然后您可以在您的preference.xml 中使用该类,如下所示:
<com.yourApplicationName.myPreferenceList
android:key="yourKey"
android:entries="@array/yourEntries"
android:entryValues="@array/yourValues"
android:title="@string/yourTitle" />