java-Android中偏好设置活动的onclick侦听器
作者:互联网
我遵循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中实现点击侦听器?
解决方法:
在SettingsActivity的onCreate()方法中:
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;
}
});
标签:android-activity,android-preferences,java,android 来源: https://codeday.me/bug/20191027/1941007.html