Search code examples
androidandroid-preferencesandroid-dialogfragmentandroid-dialog

How can I hide Dialog of ListPreference or prevent opening it in setOnPreferenceClickListener method but not disabling preference of course


I want to display list of bounded bluetooth devices in ListPreference, but Bluetooth may be disabled on a device and I need to enable it first, I call intent for enabling BT on preference click and of course dialog popups of this preference

listPreference.setOnPreferenceClickListener {
    if (!btAdapter.isEnabled) {
        val enableAdapter = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
        if (enableAdapter.canBeHandled(context.packageManager)) {
            startActivityForResult(enableAdapter, BLUETOOTH_REQUEST_ENABLE_CODE)
        }
    }
    true
}

How can I dismiss this dialog or prevent showing it at some conditions (!btAdapter.isEnabled)?


Solution

  • decided to create custom class:

    class ListPreferenceActiveControl : ListPreference {
    
        var isActive = true
    
        constructor(context: Context?) : super(context)
    
        constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
    
        constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(
            context,
            attrs,
            defStyleAttr
        )
    
        override fun onClick() {
            if (isActive) {
                super.onClick()
            }
        }
    }
    

    and then:

    listPreference.isActive = btAdapter.isEnabled