Reputation: 926
I'm using PreferenceFragmentCompat
from the Android Support Library and I've encountered a weird issue. When the fragment loads, the switches on the SwitchPreference
elements that I am using show up right next to the text, which is the wrong place. If I tap on one switch or scroll so that the switch is out of view, it fixes itself. Note: this occurs on API 25, but not API 18.
On load:
After tap or scroll:
Have any thoughts on what is going on? Any help is appreciated!
Here is what I have done:
SwitchPreferenceCompat
invalidate()
on the Fragment's view to force a redraw (hoping it would work like scrolling does to fix it)Code to create preferences (in Kotlin):
class PreferencesFragment : PreferenceFragmentCompat(), SharedPreferences.OnSharedPreferenceChangeListener {
override fun onCreatePreferences(bundle: Bundle?, s: String?) {
val deviceCategory = PreferenceCategory(activity)
deviceCategory.title = activity.getString(R.string.preferences_Device_Defaults)
preferenceScreen.addPreference(deviceCategory)
val clockPref = SwitchPreference(activity)
clockPref.title = activity.getString(R.string.preferences_Automatic_clock_synchronization)
clockPref.isChecked = true
clockPref.key = "clockSync"
deviceCategory.addPreference(clockPref)
// Add more preferences....
val unitCategory = PreferenceCategory(activity)
unitCategory.title = activity.getString(R.string.preferences_Unit_Defaults)
preferenceScreen.addPreference(unitCategory)
val runCellTestOnConnect = SwitchPreference(activity)
runCellTestOnConnect.title = activity.getString(R.string.preferences_Cell_network_check)
runCellTestOnConnect.isChecked = true
runCellTestOnConnect.key = "runCellTestOnConnect"
unitCategory(runCellTestOnConnect)
// Add more preferences....
}
}
Upvotes: 0
Views: 654
Reputation: 11
I met exactly the same issue when developing in Kotlin. Currently I have a temporary workaround: creating an empty preference before all the other preferences, and filling a long invisible string in its summary.
For example, assume that I'm using a XML file to construct the preferences:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<Preference
android:key="pref_static_field_key"
android:persistent="false"
android:selectable="false"
android:summary="@string/spaces" />
<!-- Other Preferences -->
</PreferenceScreen>
Then you will notice that the width of the following SwitchPreference elements are determined by the width of this empty Preference. If the "@string/spaces" is long enough (e.g. multiple lines or at least as long as the whole screen), you can get correct width.
Upvotes: 1