I've been trying to reference a TextView inside an XML file that's used inside a Preference tag. Below is a simplified version of my file structure:
primary.xml
<PreferenceScreen
.
.
.
<PreferenceCategory
.
.
.
<Preference
android:key="pref_key"
android:layout="@layout/custom_layout"
</Preference>
custom_layout.xml
<LinearLayout
<TextView
android:id="@ id/my_text_view"
</TextView>
</LinearLayout>
primary_fragment.kt
class PrimaryFragment : PreferenceFragmentCompat() {
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
setPreferencesFromResource(R.xml.primary.xml, rootKey) // renders primary.xml perfectly as well as primary.xml's preference who refers to custom_layout!
.
.
.
}
I have also had no issues referencing the specific Preference tag to attach an onClickListener inside primary_fragment.kt. For example,
findPreference<Preference>("pref_key")?.apply {
setOnPreferenceClickListener {
Log.d("debug", "onClick working!") // this works!
true
}
}
However, I'm unable to reference the TextView with id "my_text_view" inside primary_fragment.kt. I've tried overriding several methods from the super class and haven't been successful with findViewById(...) in any of them. My ultimate goal is to get reference to this TextView and hide it when the user clicks on the Preference. I have seen several other threads about this issue but most seem outdated and have little explanation.
CodePudding user response:
Solved by creating a CustomPreference class that extends Preference
class MyCustomPreference @JvmOverloads constructor(
context: Context,
val attr: AttributeSet? = null,
private val defStyleAttr: Int = 0
) : Preference(context, attr, defStyleAttr) {
init {
layoutResource = R.layout.my_preference_layout
}
override fun onBindViewHolder(holder: PreferenceViewHolder) {
super.onBindViewHolder(holder)
with(holder.itemView.findViewById<TextView>(R.id.my_text_view)) {
// code here to modify TextView
}
}
}
Reference this Preference as such
findPreference<MyCustomPreference>(getText(R.string.my_custom_preference_key))?.apply {
// your code here (ex: setup onClickListener)
}