Talk about the use examples of context in Android

Hello, today I'd like to share some usage of context in Android. In the past, people often asked me in the group. For example, I need to call context in a tool class or view. But what if there is no context in the tool class and view? In order to solve your questions and solve your questions, I'll write a simple demo today. Let's learn how to use context freely. When you want to have context, there will be context

There are two types: one is to pass the context parameter, and the other is to call the global context

In fact, when our application starts, we will start the application class. This class is the default in the androidmanifest.xml file

This application class is a singleton, that is, we can write an application (for example, mainapplication) class to replace the default applicaiton. This class can save the global variables of the application, and we can define a global context for external calls. The usage is as follows:

We need to register mainapplication in androidmainifest.xml (line 10):

In order to make it easier for everyone to understand, I wrote a simple demo. The steps are as follows:

Step 1: create an Android project applicationdemo. The directory structure is as follows:

Step 2: create a new mainapplication. Java. The code is the same as above, so I won't post it

Step 3: create a new tool class toolsutil.java with the following code

Step 4: create a new view named mainview.java, which is the real view of our activity. The code is as follows:

Here, the layout main.xml code used by mainview.java is as follows:

Step 5: modify applicationdemoctivity.java. The code is as follows:

Step 6: run the above project, and the results are as follows:

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>