我遵循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中实现点击侦听器?
最佳答案
在onCreate()
的SettingsActivity
方法中:
Preference preference = findPreference("prefs_key");
preference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
Toast.makeText(SettingsActivity.this, "Clicked", Toast.LENGTH_SHORT).show();
return true;
}
});