Talk about the use case of the context in Android _android

Source: Internet
Author: User

Hello everyone, today to share some of the android context of the use of some of the past, often people in the group asked me for example, I am in a tool class in a method, or view needs to invoke the context. But what about the tool class and the view? In order to solve everyone's question, in order to solve the question, I write a simple demo today. Let everyone how to learn freely with the context. When you want to have a context, when there is a context.

Here can be divided into two types: one is to pass the context parameters, the other is to invoke the global context.

In fact, when we start the application will start application This class, this class is in the Androidmanifest.xml file is actually the default

<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= "Androidintentactionmain"/> <category 
        " Androidintentcategorylauncher "/> 
      </intent-filter> 
    </activity> 
  

This application class is a single example, which means that we can write a application (such as a mainapplication) class to replace the default Applicaiton, which can save the applied global variables. We can define a global context. For external calls. The usage is as follows:

Package com.tutor.application; 
 
Import androidappapplication; 
Import Androidcontentcontext; 
 
public class MainApplication extends application { 
 
  /** 
   * Global Context * 
  /private static contexts Mcontext; 
   
  @Override public 
  void OnCreate () { 
    superoncreate (); 
     
    Mcontext = Getapplicationcontext (); 
     
  }   
   
  /** Get Context 
   * @return 
   * 
  /public static Context GetContext () {return 
    mcontext; 
  } 
   
   
  @Override public 
  void Onlowmemory () { 
    superonlowmemory (); 
  } 
   
   
} 

We need to register MainApplication in Androidmainifest.xml (line 10th code):

<?xml version= "1.0" encoding= "Utf-8"?> <manifest xmlns:android= 
"http://schemasandroidcom/apk/res/" Android " 
  package=" comtutorapplication " 
  android:versioncode=" 1 " 
  android:versionname=" 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=" Androidintentactionmain "/> 
        <category android:name= "Androidintentcategorylauncher"/> 
      </intent-filter> 
    </ activity> 
  </application> 
   
</manifest> 

To make it easier for everyone to understand, write a simple demo. The steps are as follows:

First step: Create a new Android project Applicationdemo, the directory structure is as follows:

The second step: New Mainapplication.java, code and the same as above I will not post.

Step three: Create a new tool class Toolsutil.java with the following code

Package com.tutor.application; 
Import Androidcontentcontext; 
Import Androidwidgettoast; 
 
/** 
 * @author Frankiewei 
 * Application of some tool classes/public 
class Toolutils { 
   
  /** 
   * Parameters with context 
   * @param Context 
   * @param msg 
  /public static void Showtoast (Context context,string msg) { 
    Toastmaketext ( Context, MSG, toastlength_short) show (); 
  } 
   
  /** 
   * Invokes the global context 
   * @param msg 
  /public static void Showtoast (String msg) { 
    Toastmaketext ( Mainapplicationgetcontext (), MSG, toastlength_short) show (); 
  } 
 

Fourth step: Create a view named Mainview.java is our Activity reality view. The code is as follows:

Package com.tutor.application; 
Import androidappactivity; 
Import Androidcontentcontext; 
Import Androidutilattributeset; 
Import Androidviewlayoutinflater; 
Import Androidviewview; 
Import Androidwidgetbutton; 
 
Import Androidwidgetframelayout; /** * @author Frankiewei * Custom Mainview/public class Mainview extends Framelayout implements Viewonclicklistener 
   
  {Private context Mcontext; 
   
  Private activity mactivity; 
   
  /** * Parameter button */private button Margbutton; 
   
  /** * Global button */private button Mgloblebutton; 
   
  /** * Exit button */private button Mexitbutton; 
    Public Mainview {Super (context); 
  Setupviews (); 
    Public Mainview (context, AttributeSet attrs) {Super (context, attrs); 
  Setupviews (); 
    private void Setupviews () {//Gets the context of the view Mcontext = GetContext (); 
    Here the context is converted to activity mactivity = (activity) Mcontext; LayoutinFlater inflater = Layoutinflaterfrom (Mcontext); 
    View v = inflaterinflate (rlayoutmain, NULL); 
     
    AddView (v); 
    Margbutton = (Button) Vfindviewbyid (Ridarg_button); 
    Mgloblebutton = (Button) Vfindviewbyid (Ridglo_button); 
     
    Mexitbutton = (Button) Vfindviewbyid (Ridexit_button); 
    Margbuttonsetonclicklistener (this); 
    Mgloblebuttonsetonclicklistener (this); 
  Mexitbuttonsetonclicklistener (this); The public void OnClick (View v) {if (v = = Margbutton) {toolutilsshowtoast (Mcontext, "I was shown by passing the context parameter!") 
    ; 
    }else if (v = = Mgloblebutton) {toolutilsshowtoast ("I was shown through the global context!"); 
    }else{Mactivityfinish (); 
 } 
  } 
 
}

The layout Mainview.java used here Main.xml code as follows:

 <?xml version= "1.0" encoding= "Utf-8"?> <linearlayout "xmlns:android=" Schemasandroidcom/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_co" 
    Ntent "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= "Pass context parameters"/> 
   
  ; <button android:id= "@+id/glo_button" android:layout_width= fill_parent "android:layout_height=" Wrap_cont ENT "android:text=" Global Context "/> <button android:id=" @+id/exit_button "Android:layout_wi 
Dth= "Fill_parent" android:layout_height= "Wrap_content" android:text= "Exit App"/> </LinearLayout> 

Fifth step: Modify Applicationdemoactivity.java, the code is as follows:

Package com.tutor.application;  
Import androidappactivity; 
Import Androidosbundle; 
 
public class Applicationdemoactivity extends activity { 
  @Override public 
  void OnCreate (Bundle Savedinstancestate) { 
    superoncreate (savedinstancestate); 
     
    Mainview Mmainview = new Mainview (this); 
    Setcontentview (Mmainview); 
   
  } 
   

The sixth step: the operation of the above works effect is as follows:

Run effect 1

Run Effect 2----Click on the first button

Run Effect 3----Click on the second button

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.