Create a gist now

Instantly share code, notes, and snippets.

class SettingFragment : PreferenceFragmentCompat() {
companion object {
fun newInstance(rootKey: String?): SettingFragment = SettingFragment().apply {
arguments = Bundle().apply {
putString(PreferenceFragmentCompat.ARG_PREFERENCE_ROOT, rootKey)
}
}
}
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
setPreferencesFromResource(R.xml.setting, rootKey)
}
}
class SettingActivity: AppCompatActivity(), PreferenceFragmentCompat.OnPreferenceStartScreenCallback {
override fun onPreferenceStartScreen(fragment: PreferenceFragmentCompat, screenPreference: ScreenPreference) : Boolean = true.apply {
supportFragmentManager.beginTransaction().replace(R.id.container, SettingFragment.newInstance(screenPreference.key).addToBackStack(null).commit()
}
}
class SettingFragment : PreferenceFragmentCompat() {
private val stack: Stack<String?> = Stack()
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
addPreferencesFromResource(R.xml.setting)
}
override fun onNavigateToScreen(preferenceScreen: PreferenceScreen) {
stack.push(this.preferenceScreen.key)
setPreferencesFromResource(R.xml.setting, preferenceScreen.key)
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
view?.isFocusableInTouchMode = true
view?.requestFocus()
view?.setOnKeyListener { view, action, event ->
((action == KeyEvent.KEYCODE_BACK) and stack.isNotEmpty()).apply {
if (this) {
setPreferencesFromResource(R.xml.setting, stack.pop())
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment