androidbuttonandroid-buttonledandroid-things

why button.ispressed() doesn't work on android things


Hi I'm trying to light up led on android thing only when pressing the button(not physical button) so I tried this code below but it doesn't work for the method it's not pressed: I want to be led turn on only as long as I'm pressing the button

button.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View view) {

                if(!button.isPressed()){
                try {

                    mLightGpio = mPeripheralManager.openGpio("BCM3");
                    mLightGpio.setDirection(Gpio.DIRECTION_OUT_INITIALLY_HIGH);


                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
              else
                  {
                   try {
                       mLightGpio = mPeripheralManager.openGpio("BCM3");
                       mLightGpio.setDirection(Gpio.DIRECTION_OUT_INITIALLY_LOW);

                   } catch (IOException e) {
                       e.printStackTrace();
                   }
                }
            }

        });
    }

Solution

  • Because onClick invokes only once. I would suggest to light up the led when the button is pressed (ACTION_DOWN) and turn it off when it's released (ACTION_UP).

    Use something like this:

    button.setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction() ) {
                case MotionEvent.ACTION_DOWN:
                    // light up
                break;
    
                case MotionEvent.ACTION_UP:
                    // turn off
                break;
            }
    
            return false;
        }
    });