未检测到优先选择

时间:2015-10-29 17:29:06

标签: android onclick onclicklistener android-preferences preferenceactivity

我为偏好设置了一个onpreference点击监听器,但即使找到偏好命令找到了偏好,也无法触发。

活动

public class PreferenceActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Display the fragment as the main content
        setContentView(R.layout.activity_preference);
        if (savedInstanceState == null) {
            getFragmentManager().beginTransaction()
                    .replace(R.id.settings, new SettingsFragment())
                    .commit();
        }
    }

    public static class SettingsFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {

        Context context;
        private final String DOB = "date";
        private SharedPreferences prefs;

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.preferences);

            context = getActivity().getApplicationContext();

            Preference dob = findPreference(DOB);
            Log.i("test", dob.getKey() + "");

            dob.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
                @Override
                public boolean onPreferenceClick(Preference preference) {
                    Log.i("test", "2");
                    return false;
                }
            });


        }

        @Override
        public void onPause() {
            super.onPause();
            getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
        }

        @Override
        public void onResume() {
            super.onResume();
            getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
        }
    }
}

首选项xml

    <?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

    <PreferenceCategory android:title="My Account">

        <EditTextPreference
            android:key="profile_name"
            android:summary="Taylor Swift"
            android:title="Username" />

        <Preference
            android:key="date"
            android:summary="N.A."
            android:title="@string/date" />

    </PreferenceCategory>

</PreferenceScreen>

“test”的日志输出正确显示首选项的键,但onclick中的日志永远不会触发。

1 个答案:

答案 0 :(得分:0)

我用你的代码创建了一个简单的项目,一切似乎都运行正常。

Log.i("test", "2");
点击&#34;日期&#34;正在调用

字段。