Android将ChangeListener设置为首选项

时间:2014-03-22 03:38:27

标签: android preference

我正在尝试在单击首选项时打开对话框。结果。它什么都不做。 这是偏好活动

public class SettingsPrefActivity extends PreferenceActivity {
    ...
    Preference.OnPreferenceChangeListener changeInfoListener = new Preference.OnPreferenceChangeListener() {
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            Log.i("TAG","Click in Pref");
            dialogCustom(findViewById(android.R.id.content));
            return true;
        }
    };

    Preference prefInfo = (Preference) findPreference("pref_info");
    prefInfo.setOnPreferenceChangeListener(changeInfoListener);

}   

public void dialogCustom(View v) {
    Log.i("TAG","Dialog");
    final Dialog dialog = new Dialog(getApplicationContext());
    dialog.setContentView(R.layout.dialog_info);
    dialog.setTitle("INFORMATION");
    dialog.setCancelable(true);
    Button button = (Button) dialog.findViewById(R.id.buttonOK);
    button.setOnClickListener(new View.OnClickListener() {
       public void onClick(View v) {
           dialog.dismiss();
           }
       });
       dialog.show();
}

这是pref xml的一部分

<PreferenceCategory 
    android:title="ABOUT"
    android:key="about_category"
    android:layout="@layout/prefcatcustomlayout"
    >
   <Preference
       android:key="pref_version"
       android:title="Version"
       android:summary="1.0"
   />
   <Preference
       android:key="pref_info"
       android:title="Information"
       android:summary=""
   />
</PreferenceCategory>

1 个答案:

答案 0 :(得分:1)

您必须使用prefInfo.setOnPreferenceClickListener

使用此代码......

public class SettingsPrefActivity extends PreferenceActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    addPreferencesFromResource(R.xml.prefs);

    Preference prefInfo = (Preference) findPreference("pref_info");
    prefInfo.setOnPreferenceClickListener(clickListener);

}


Preference.OnPreferenceClickListener clickListener = new Preference.OnPreferenceClickListener() {
    @Override
    public boolean onPreferenceClick(Preference preference) {
        Log.i("TAG", "Click in Pref");
        dialogCustom(findViewById(android.R.id.content));
        return true;
    }
};


public void dialogCustom(View v) {
    Log.i("TAG","Dialog");
    AlertDialog.Builder builder = new AlertDialog.Builder(this)
            .setTitle("INFORMATION");

    builder.setNeutralButton("OK",new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog,int which) {
                dialog.dismiss();
        }}).show();
}
}