Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 572
Leo Avatar asked Feb 10 '26 16:02

Leo


1 Answers

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);
    }
}
like image 135
ento Avatar answered Feb 13 '26 10:02

ento



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!