Tuesday, August 25, 2015

How to Enable or Disable a button in runtime in Android

While I was working with an Android application for a customer, there was a use case to disable a button in the run time. And need to enable it after some action. We can do it very easily in Android.

I have a “About” button in the screen. And I need to enable and disable the button based on the network status. In xml, we have the button as below:

        android:text="@string/about_label" />     

You need to reference it in the activity using findViewById in onCreate() method:

View aboutButton = findViewById(R.id.about_button);

You can enable or disable by setting  setEnabled() to true or false.

To enable: setEnabled(true);
And to disable: setEnabled(false);


Now, I am going to enable it if the connectivity is available. I have added a class- NetworkUtil to check the network status. You can download it from here. (NetworkUtil) and use it in your activity to check the status. You need to create an object for this class and use the method: getConnectivityStatus. Here is the code to do so:

NetworkUtil net =new NetworkUtil();
      int status = net.getConnectivityStatus(getApplicationContext());

That’s it. Happy Coding..

No comments: