Skip to content

Preference

kevadiya krunal edited this page Mar 28, 2019 · 2 revisions

Preference bind methods can be used with Context, Fragment, support library Fragment, View, and ViewHolder subclasses. The example below uses a default SharedPreferences instance. You can always provide a custom one by implementing PreferencesAware interface.

Although only Boolean, Float, Int, Long, String and Gson preferences are supported by default, the library can be easily extented to support custom type of preference. Adapter interface can be implemented in order to convert any type to a supported one. Here is an example how to imlement json-based preferences using Gson.

  • In Activity use.
// Below example is used default share-preference to save local info.
// Here is my custom data class.
data class Profile(val firstName: String? = null, val lastName: String? = null)
class PreferenceActivity : AppCompatActivity() {
    // Boolean preference
    var boolean by bindPreference<Boolean>(false, "boolean")

    // Float preference
    var float by bindPreference<Float>(0.0f, "float")

    // Integer preference
    var integer by bindPreference<Int>(1, "integer")

    // Long preference
    var long by bindPreference<Long>(1L, "long")

    // String preference
    var string by bindPreference<String>("default", "string")

    // Any custom class can save to preference
    var profile by bindGsonPreference(Profile())

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_preference)
        ...........
    }
}
  • In Fragment use.
// Below example is custom share-preference used.
class PreferencesFragment : Fragment() {
    companion object {
        fun newInstance(): PreferencesFragment = PreferencesFragment()
    }

    val preferences = PreferencesAware {
        activity!!.getSharedPreferences("CustomSharedPreferences", Context.MODE_PRIVATE)
    }

    var boolean by preferences.bindPreference<Boolean>(false, "boolean")
    var float by preferences.bindPreference<Float>(0.0f, "float")
    var integer by preferences.bindPreference<Int>(1, "integer")
    var long by preferences.bindPreference<Long>(1L, "long")
    var string by preferences.bindPreference<String>("default", "string")

    // Optional preferences are supported as well
    var optionalLong by preferences.bindOptionalPreference<Long>()
    var optionalString by preferences.bindOptionalPreference<String>()

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.activity_preference, container, false)
    }
}

Clone this wiki locally