从自定义首选项获取视图

Cil*_*nco 7 android android-preferences android-xml

在我的应用程序中,我有一个PreferenceScreen,如下所示:

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
    <CheckBoxPreference
            android:key="state"
            android:title="@string/stateTitle"
            android:summary="@string/stateSummary"
            android:defaultValue="false" />

    <Preference
            android:key="test"
            android:layout="@layout/pref_control"
            android:dependency="state" />
</PreferenceScreen>
Run Code Online (Sandbox Code Playgroud)

现在我的问题是如何pref_control.xml从PreferenceActivity 获取我的观点?我尝试了正常,findViewById()但结果是NullPointerException.这是导致异常的代码:

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.preferences);

    ((Button) findViewById(R.id.startTime)).setText("bla");
    ((Button) findViewById(R.id.endTime)).setText("bla");
}
Run Code Online (Sandbox Code Playgroud)

Dav*_*ite -1

由于您使用的是 PreferenceActivity,因此您可以使用:

final CheckBoxPreference stateCheckBox = (CheckBoxPreference)findPreference("state");
Run Code Online (Sandbox Code Playgroud)

大概:

final Preference testPreference = (Preference)findPreference("test");
Run Code Online (Sandbox Code Playgroud)

它已被弃用,但应该可以工作。