During normal development, we may sometimes need some global data to make all the activities and views in the application accessible. In this case, you may first want to define a class and then create many static members. However, Android has provided us with a solution to this problem. Here we will introduce it:
In Android, there is a class named application. We can use the getapplication () method in the activity to obtain the class that represents our application, you can use it to obtain the topic of the current application and the content in the resource file. A more flexible feature of this class is that it can be inherited by us to add our own Global attributes. For example, if we are developing a game application and need to save scores, We can inherit the application. The Code is as follows:
[Java]
View plaincopy
- Public class gameapplication extends application {
- Private int score;
- Public int getscore (){
- Return score;
- }
- Public void setscore (INT score ){
- This. Score = score;
- }
- }
In this way, we have extended our attributes, but it is not over yet. Another key step is to use androidmanifest. specify the Extended Application class in the XML file, for example, the following code:
[XHTML]
View plaincopy
- <Application
- Android: Name = ". gameapplication"
- Android: icon = "@ drawable/icon"
- Android: Label = "@ string/app_name">
After this is specified, our custom application is completed, and then we can easily obtain our score attributes in any activity and view. The Code is as follows:
In activity:
[C-sharp]
View plaincopy
- // Set the score
- (Gameapplication) getapplication (). setscore (100)
- // Obtain the score
- (Gameapplication) getapplication (). getscore ();
In View:
[Java]
View plaincopy
- (Gameapplication) getcontext (). getapplicationcontext (). getscore ()