In my mind, a private function can only be accessed inside a class, but in my example the following code bindPreferenceSummaryToValue(findPreference("RestoreItem"))
, which is outside the companion object, is accessible. Why?
Code
class UIPreference : AppCompatPreferenceActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.layout_preference)
fragmentManager.beginTransaction().replace(R.id.content, MyPreferenceFragment()).commit()
setControl()
utility.setAD(adView)
}
class MyPreferenceFragment : PreferenceFragment() {
private lateinit var mContext: Context
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
addPreferencesFromResource(R.xml.mypreference)
mContext=this.activity
setPreference()
bindPreferenceSummaryToValue(findPreference("RestoreItem"))
}
}
companion object {
private val sBindPreferenceSummaryToValueListener = Preference.OnPreferenceChangeListener { preference, value ->
val stringValue = value.toString()
if (preference is ListPreference) {
val listPreference = preference
val index = listPreference.findIndexOfValue(stringValue)
preference.setSummary(
if (index >= 0)
listPreference.entries[index]
else
preference.summary)
}
true
}
private fun bindPreferenceSummaryToValue(preference: Preference) {
preference.onPreferenceChangeListener = sBindPreferenceSummaryToValueListener
sBindPreferenceSummaryToValueListener.onPreferenceChange(preference,
PreferenceManager
.getDefaultSharedPreferences(preference.context)
.getString(preference.key, ""))
}
}
}
To David Rawson
Thanks! But from https://kotlinlang.org/docs/reference/visibility-modifiers.html, it seems that "private means visible inside this class only (including all its members);" for Classes and Interfaces.
Would you please see the image?
To yole:
Thanks! I can't access a private member in the class MyB outside companion object by the following code.
class UIPreference {
companion object {
private val aa=1
}
class MyA {
private val bar: Int =UIPreference.aa //OK
}
}
class MyB {
private val bar: Int = UIPreference.aa //Failed
}