以下是猜测我的PreferenceFragment的工作代码它不会产生任何错误,但似乎也没有做任何事情:)这个ListPreference的静态xml版本是显示的内容。为了简化下面的例子,我展示了一系列字符串"条目"和" entryValues"填充ListPreference但最终将从我的数据模型中检索这些。
public class UserSettingsFragment : PreferenceFragment
{
public override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Load the preferences from an XML resource
AddPreferencesFromResource(Resource.Xml.UserSettings);
// http://stackoverflow.com/questions/5375363/dynamic-listpreference-in-android
//var lp = new ListPreference(Context);
//var lp = FindViewById<ListPreference>(0); // "prefSoundPack"
// var lp = FindPreference("prefSoundPack").Context;
var lp = new ListPreference(FindPreference("prefSoundPack").Context);
lp.PreferenceClick += lp_PreferenceClick;
}
void lp_PreferenceClick(object sender, Preference.PreferenceClickEventArgs e)
{
var lp = new ListPreference(e.Preference.Context);
String[] entries = { "Pack1", "Pack2" };
String[] entryValues = { "0", "1" };
lp.SetEntries(entries);
lp.SetEntryValues(entryValues);
}
}
我的UserSettings.xml类似于
<PreferenceCategory android:title="@string/pref_Sound_settings">
<ListPreference android:key="prefSoundPack"
android:title="@string/pref_SoundPacks_title"
android:summary="@string/pref_SoundPacks_summary"
android:defaultValue="1"
android:entries="@array/SoundPacks"
android:entryValues="@array/SoundPacksValues" >
</ListPreference>
</PreferenceCategory>
答案 0 :(得分:2)
因为没有答案;这应该在您的OnCreate方法内部工作:
ListPreference preference = (ListPreference) FindPreference("key");
preference.SetEntries(new String[] {"Pack 1", "Pack 2"});
preference.SetEntryValues(new String[] {"0", "1"});