Tord Larsen
Tord Larsen

Reputation: 2836

How to access custom Preference class from inside PreferenceFragmentCompat

I need to call a method in my custom 'android.support.v7.preference.Preference' class.

I added the Preferences class like this:

addPreferencesFromResource(R.xml.app_prefs)

R.xml.app_prefs:

    <PreferenceCategory
        android:layout="@layout/pref_category_text"
        android:title="@string/pref_category_stat_out_title">
        <com.sun.preferences.CustomPreference android:key=" @string/pref_key_show_stat" />
    </PreferenceCategory>

You see the the CustomPreference above:

It has this method CallMee() like this really simple I removed stuff for simplicity:

public class CustomPreference extends Preference {

  public CustomPreference(Context context) {
     super(context);
  }

  public void CallMee(){

  }
}

I have tried in the PreferenceFragmentCompat to use the method:

override fun setUserVisibleHint(isVisibleToUser: Boolean) {
    super.setUserVisibleHint(isVisibleToUser)

   if(isVisibleToUser)
     // call method CallMee() inside `CustomPreference` but how?

}

Since this custom CustomPreference is added from the addPreferencesFromResource(R.xml.app_prefs)

I dont understand how to call it! Is it possible?

Upvotes: 1

Views: 137

Answers (1)

Harsh Modani
Harsh Modani

Reputation: 221

You have to construct an instance of your custom preference in the block of if (isVisibleToUser).

Try in your PreferenceFragmentCompat subclass,

CustomPreference pref = findPreference(getString(R.string.pref_key_show_stat));
pref.CallMee();

Upvotes: 1

Related Questions