How to open ListPreference immediately when activity is created?

时间:2016-08-31 18:12:57

标签: android android-preferences listpreference

I have an application with two screens, MainActivity - screen with buttons, and SecondActivity - settings screen. In this SecondActivity I have one ListPreference.

How to open this ListPreference when SecondActivity is opening?

1 个答案:

答案 0 :(得分:0)

首先,您需要计算ListPreferencePreferenceScreen位置。然后尝试以下代码:

PreferenceScreen main = (PreferenceScreen)findPreference(getString(R.string.pref_screen_root));
    main.onItemClick(null, null, pos, 0);

此处 pos ListPreferencePreferenceScreen 位置 R.string.pref_screen_rootPreferenceScreen的关键。

以下是最简单的xml文件:

  <?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
    android:key="@string/pref_screen_root" >
 <ListPreference
            android:defaultValue="0"
            android:entries="@array/list_entries"
            android:entryValues="@array/list_values"
            android:icon="@drawable/ic_earth"
            android:key="@string/pref_country"
            android:title="Select a country" />
</PreferenceScreen>