Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get View from custom Preference

In my app I have a PreferenceScreen which looks like this:

<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>

Now my question is how can I get the views which are in my pref_control.xml from the PreferenceActivity? I tried with normal findViewById() but that ends in a NullPointerException. Here is my code that causes the exception:

@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");
}
like image 700
Cilenco Avatar asked Mar 27 '14 14:03

Cilenco


1 Answers

You can get the Preference by using Preference p = findPrefences("test") from the Activity (or better the PreferenceFragment, if you are using newer versions of Android).

On that object you can call .getView(convertView, parent). For your purposes, it should be ok to call that method with null as paramters: findPreferences("test").getView(null, null).

HTH

like image 171
BuZZ-T Avatar answered Sep 29 '22 05:09

BuZZ-T