Home > Software design >  How to enable or disable a button according to System time in Android?
How to enable or disable a button according to System time in Android?

Time:02-23

I want to enable the button in Android from 9.00 AM to 9.30 AM in the morning and from 5.00 PM to 5.30 PM in the afternoon in Android. Rest of the time, I want the button to be disabled. How can I do this in Java?

CodePudding user response:

Here is a possible Kotlin implementation:

val currentHour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY)
val currentMinute = Calendar.getInstance().get(Calendar.MINUTE)
val isButtonEnabled = currentMinute <= 30 && (currentHour == 9 || currentHour == 17)
button.isEnabled = isButtonEnabled

CodePudding user response:

this is a function which is returning current time in 24hours formate


    public  String getCurrentHHMMSS_24() {
        String currentDateAndTime = new SimpleDateFormat("HH:mm:ss").format(new Date());
        return currentDateAndTime;


    }

// function which return true and false acording to your time

    public  boolean buttoncheck() {
        boolean enablebutton=false;
        String[] splittime=getCurrentDateHHMMSS_24().split(":");
        if ((splittime[0].equals("09") ||  (splittime[0].equals("17"))) && splittime[1].equals("30" )) 
        {
            enablebutton=true;
        }

        return enablebutton;
    }

  • Related