Replace enumeration with annotation @ IntDef
Keywords:
Android
Programming
Before we start, let's take a look at a paragraph in the official Android documentation.
Be careful with code abstractions
Developers often use abstractions simply as a good programming practice, because
abstractions can improve code flexibility and maintenance. However, abstractions
come at a significant cost: generally they require a fair amount more code that
needs to be executed, requiring more time and more RAM for that code to be mapped
into memory. So if your abstractions aren't supplying a significant benefit, you
should avoid them.
For example, enums often require more than twice as much memory as static constants. You should strictly avoid using enums on Android
The official saying is: when we write code, we should pay attention to the use of types in order to improve the scalability and maintainability of the code, but the use of prototypes generally costs more memory, so if there is no great advantage, we should try to avoid using them. For enumeration, the memory occupied is often two times that of using static constants, so we should try to avoid using enumeration in Android.
So using @ IntDef annotation instead of enumeration is a good choice.
First, add android annotation dependency:
compile 'com.android.support:support-annotations:25.1.0'
The specific usage is as follows:
public class MainActivity extends AppCompatActivity{
public static final int STATE_NONE = -1;
public static final int STATE_LOADING = 0;
public static final int STATE_SUCCESS = 1;
public static final int STATE_ERROR = 2;
public static final int STATE_EMPTY = 3;
private @State int state;
public void setState(@State int state){
this.state = state;
}
@State
public int getState() {
return this.state;
}
@IntDef({STATE_EMPTY, STATE_ERROR, STATE_LOADING, STATE_NONE, STATE_SUCCESS})
@Retention(RetentionPolicy.SOURCE)
public @interface State {
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
Posted by fross on Thu, 09 Apr 2020 09:04:45 -0700