Let's talk about the use of context in Android !!!

Source: Internet
Author: User

Hello everyone, today I want to share with you some usage of context in Android. In the past, people often asked me in groups, for example, a method in a tool class, or the context needs to be called in a view. but what should I do if there is no context in the view in the tool class? To solve your questions and solve your questions, I will write a simple demo today. let everyone learn how to use context freely. I want to know when context exists and when context exists.

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

In fact, the application class will be started when the application is started. This class is actually the default in the androidmanifest. xml file.

 <application        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        >        <activity            android:name=".ApplicationDemoActivity"            android:label="@string/app_name" >            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>    </application>

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

Package COM. tutor. application; import android. app. application; import android. content. context; public class mainapplication extends application {/*** global context. */Private Static Context mcontext; @ overridepublic void oncreate () {super. oncreate (); mcontext = getapplicationcontext () ;}/ ** get context. * @ return */Public Static Context getcontext () {return mcontext;} @ overridepublic void onlowmemory () {super. onlowmemory ();}}

We need to register the mainapplication in androidmainifest. XML (10th lines of code ):

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.tutor.application"    android:versionCode="1"    android:versionName="1.0" >        <application        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:name=".MainApplication" >        <activity            android:name=".ApplicationDemoActivity"            android:label="@string/app_name" >            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>    </application></manifest>

To make it easier 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 mainapplication. java. I will not post the same code as above.

Step 3: Create a toolsutil. Java tool. The Code is as follows:

Package COM. tutor. application; import android. content. context; import android. widget. toast;/*** @ author frankiewei. * Some tool classes of the application. */public class toolutils {/*** parameter with context. * @ Param context * @ Param MSG */public static void showtoast (context, string MSG) {toast. maketext (context, MSG, toast. length_short ). show ();}/*** call the global context. * @ Param MSG */public static void showtoast (string MSG) {toast. maketext (mainapplication. getcontext (), MSG, toast. length_short ). show ();}}

Step 4: Create a view named mainview. Java is the actual view of the activity. The Code is as follows:

Package COM. tutor. application; import android. app. activity; import android. content. context; import android. util. attributeset; import android. view. layoutinflater; import android. view. view; import android. widget. button; import android. widget. framelayout;/*** @ author frankiewei. * Custom mainview. */public class mainview extends framelayout implements view. onclicklistener {private context mcontext; private activ Ity mactivity;/*** parameter button. */private button margbutton;/*** global button. */private button mgloblebutton;/*** exit the button. */private button mexitbutton; Public mainview (context) {super (context); setupviews ();} public mainview (context, attributeset attrs) {super (context, attrs ); setupviews ();} private void setupviews () {// get the view context. mcontext = getcontext (); // here, the context is converted to activity. mactivity = (Activity) mcontext; layoutinflater Inflater = layoutinflater. from (mcontext); view v = Inflater. inflate (R. layout. main, null); addview (V); margbutton = (button) v. findviewbyid (R. id. arg_button); mgloblebutton = (button) v. findviewbyid (R. id. glo_button); mexitbutton = (button) v. findviewbyid (R. id. exit_button); margbutton. setonclicklistener (this); mgloblebutton. setonclicklistener (this); mexitbutton. setonclickliste NER (this);} public void onclick (view v) {If (V = margbutton) {toolutils. showtoast (mcontext, "it is displayed by passing the context parameter! ");} Else if (V = mgloblebutton) {toolutils. showtoast (" I display it through global context! ") ;}Else {mactivity. Finish ();}}}

The main. XML code for mainview. Java is as follows:

<? XML version = "1.0" encoding = "UTF-8"?> <Linearlayout xmlns: Android = "http://schemas.android.com/apk/res/android" Android: layout_width = "fill_parent" Android: layout_height = "fill_parent" Android: Orientation = "vertical"> <textview Android: layout_width = "fill_parent" Android: layout_height = "wrap_content" Android: text = "Welcome to Frankie Wei's blog. "/> <button Android: Id =" @ + ID/arg_button "Android: layout_width =" fill_parent "Android: layout_height =" wrap_content "Android: TEXT = "passing context parameters"/> <button Android: Id = "@ + ID/glo_button" Android: layout_width = "fill_parent" Android: layout_height = "wrap_content" Android: TEXT = "global context"/> <button Android: Id = "@ + ID/exit_button" Android: layout_width = "fill_parent" Android: layout_height = "wrap_content" Android: TEXT = "Exit app"/> </linearlayout>

Step 5: Modify applicationdemoactivity. java. The Code is as follows:

package com.tutor.application;import android.app.Activity;import android.os.Bundle;public class ApplicationDemoActivity extends Activity {    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);                MainView mMainView = new MainView(this);        setContentView(mMainView);       }    }

Step 6: perform the following operations:

Running effect 1 running effect 2 ---- click the first button

Running Effect 3 ---- click the second button

Now, let's talk about this. If you have any questions about context, please leave a message !!!

Click to enter the source code ==>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.