Android - Listen to a disabled button

前端 未结 8 2070
一整个雨季
一整个雨季 2021-01-17 08:56

How can I respond to an event based on clicking a disabled Button. I have a requirement that I have to present Dialog, when a disabled Button

相关标签:
8条回答
  • 2021-01-17 09:01

    You should use activated state to enable or disable button . It is clickable or as someone point use selected or checked state. Each of these state has a different meaning so use it carefully

    0 讨论(0)
  • 2021-01-17 09:02

    I'm about to tackle this by using the selected state, which is generally available for use in widgets, and can be used in state list drawables. A simple search for usage of isSelected turns up results in ListView, GridView, TextView and TabLayout. And the documentation states

    Views are typically * selected in the context of an AdapterView like ListView or GridView; * the selected view is the view that is highlighted.

    0 讨论(0)
  • 2021-01-17 09:04

    Instead of disabling it, keep it enabled but use a flag to control your "inner state"

    0 讨论(0)
  • 2021-01-17 09:08

    I looked for it but got nothing to listen the EditText block. So I find another way to activate it. If there is a near button or area that you already listen, you can enable SetOnLongClickListener to activate the block. It will be a secret but you can tell the users.

    button.setOnLongClickListener(new OnLongClickListener() { 
            @Override
            public boolean onLongClick(View v) {
                // TODO Auto-generated method stub
                editText.setEnabled(true)
                return true;
            }
        });
    

    enter image description here

    0 讨论(0)
  • 2021-01-17 09:10

    A disabled button cannot listen to any event, but you can customize your own button by extending Button class to make your own definition of disabling

    0 讨论(0)
  • 2021-01-17 09:17

    You can override onTouchEvent and create a listener like this :

    class MyButton @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = R.attr.materialButtonStyle) : MaterialButton(context, attrs, defStyleAttr) {
    
        private var onDisableClickListener: OnClickListener? = null
    
        override fun onTouchEvent(event: MotionEvent?): Boolean {
            if (event?.action == MotionEvent.ACTION_DOWN && !isEnabled) {
                onDisableOnClickListener?.onClick(this)
            }
            return super.onTouchEvent(event)
        }
    
        fun setOnDisableClickListener(l: OnClickListener?) {
            onDisableClickListener = l
        }
    }
    

    In your activity :

    button.setOnDisableClickListener {
                Toast.makeText(this), "The button is disabled", Toast.LENGTH_SHORT).show()
    }
    button.setOnClickListener {
                Toast.makeText(this), "The button is enabled", Toast.LENGTH_SHORT).show()
    }
    
    0 讨论(0)
提交回复
热议问题