Resource ids will be non-final by default in android gradle plugin version 8.0, avoid using them in switch case statements

Explanation:

In Android Gradle Plugin version 8.0, resource ids will be non-final by default. This means that the generated `R` class and its fields are no longer final. Previously, resource ids were final, allowing them to be used in switch case statements.

However, with non-final resource ids, using them in switch case statements can lead to compilation errors. This is because switch case statements require constant expressions, and non-final fields may not be considered constant expressions by the compiler.

Example:

Suppose we have the following resource ids in our `R` class:

    
      public static int BUTTON_OK = 1;
      public static int BUTTON_CANCEL = 2;
      public static int BUTTON_HELP = 3;
    
  

Previously, we could use these resource ids in a switch case statement like this:

    
      int buttonId = ...; // Get the button id from somewhere

      switch (buttonId) {
        case R.id.BUTTON_OK:
          // Handle OK button click
          break;
        case R.id.BUTTON_CANCEL:
          // Handle Cancel button click
          break;
        case R.id.BUTTON_HELP:
          // Handle Help button click
          break;
      }
    
  

However, with non-final resource ids in Android Gradle Plugin version 8.0, the above code will result in a compilation error.

To avoid using resource ids in switch case statements, you can use if-else statements instead:

    
      int buttonId = ...; // Get the button id from somewhere

      if (buttonId == R.id.BUTTON_OK) {
        // Handle OK button click
      } else if (buttonId == R.id.BUTTON_CANCEL) {
        // Handle Cancel button click
      } else if (buttonId == R.id.BUTTON_HELP) {
        // Handle Help button click
      }
    
  

By using if-else statements, you can still handle different cases based on the resource id without relying on switch case statements.

Related Post

Leave a comment