onclick侦听器,用于Android中的首选项活动

时间:2016-05-27 20:48:03

标签: java android android-activity android-preferences

我正在关注this documentations来创建设置页面。我根据文档创建了两个java类:

SettingsFragment.java:

public static class SettingsFragment extends PreferenceFragment {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Load the preferences from an XML resource
        addPreferencesFromResource(R.xml.preferences);
    }
    ...
}

SettingsActivity.java

public class SettingsActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Display the fragment as the main content.
        getFragmentManager().beginTransaction()
                .replace(android.R.id.content, new SettingsFragment())
                .commit();
    }
}

在首选项中,我有一个带有键premium_support的项目,我想为它创建一个点击监听器。

 <CheckBoxPreference
        android:key="@string/premium_support"
        android:title="Premium Support"
        android:summary="Purchase premium support"
        android:defaultValue="false" />

我无法在片段中创建点击监听器,因为我在 SettingsActivity 中有我的应用内帐单代码。我尝试了this answer,但似乎findPreference仅适用于preferencefragment。

知道如何在SettingsActivity中实现点击监听器吗?

2 个答案:

答案 0 :(得分:4)

onCreate()的{​​{1}}方法:

SettingsActivity

答案 1 :(得分:0)

“ findPreference”方法只能在settingsfragment上调用,因为它扩展了preferencefragment。您需要在设置活动中获得对settingsfragment类的引用,如下所示:

    private SettingsFragment settingsFragment;

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

         //instantiate the settings fragment
         settingsFragment= new SettingsFragment();
        getFragmentManager().beginTransaction()
                .replace(android.R.id.content, settingsFragment)
                .commit();
    }

然后您重写onResume并将onsetume中的preferenceclicklistener设置为onresume中,而不是oncreate中,因为commit()方法是异步调用的(即,代码不会立即执行),并且如果您在提交片段后立即调用findpreference,则首选项值可能为null oncreate中进行交易。

    @Override
        protected void onResume() {
            super.onResume();
            Preference preference = 
          settingsFragment.findPreference(getString(R.string.pref_key));
            preference.setOnPreferenceClickListener(new 
            Preference.OnPreferenceClickListener() {
                @Override
                public boolean onPreferenceClick(Preference preference) {
                   //respond to click events here
                    return true;
                }
            });

        }