Leo
Leo

Reputation: 4681

Cannot findPreference for custom preference in PreferenceActivity

I have made a custom preference layout, that has 2 toggles per row, called dualtogglepreference. Along with a class that extends Preference that handles some of the specifics for it. When I add this custom preference to my preferences.xml file it appear in the UI but I am unable to reference it using findPreference in the Preference Activity.

preferences.xml file

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory 
    android:title="Notifications">

    <com.hitpost.testing.DualTogglePreference
        android:key="followsMe"
        android:title="Someone follows me"
        android:layout="@layout/dualtogglepreference"/>

</PreferenceCategory>
</PreferenceScreen>

PreferenceActivity

public class TestingCustomPreferenceActivity extends PreferenceActivity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.preferences);

    DualTogglePreference followsMe = (DualTogglePreference) findPreference("followsMe");

    if (followsMe != null)
        Log.e("FOLLOWS_ME", "NOT NULL");
    else
        Log.e("FOLLOWS_ME", "NULL"); //THIS IS PRINTED
}
}

Visually everything looks perfect, ie the layout for the widget is correct. Please help, have been battling this for the last day.

Upvotes: 3

Views: 999

Answers (1)

ento
ento

Reputation: 5889

In my case, I had neglected to define the constructor that will be used by the inflator.

public class StaticDialogPreference extends DialogPreference {
    // this constructor is called by the infaltor
    public StaticDialogPreference(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public StaticDialogPreference(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    private void init() {
        setDialogMessage(getContext().getString(R.string.static_message));
        setNegativeButtonText(null);
    }
}

Upvotes: 2

Related Questions