分享

谈谈Android里的Context的使用!!!

 muyable 2013-12-04

大家好,今天给大家分享一下Android里的Context的一些用法,以前经常有人在群里问我比如我在一个工具类里的某个方法,或者View里需要调用Context.但是工具类还有View里没有这个上下文怎么办?为了解决大家的疑问,为了解决大家的疑问,我今天写一个简单的Demo.让大家如何学好自如的用Context.想什么时候有Context,什么时候就有Context.

这里大致可以分为两种:一是传递Context参数,二是调用全局的Context.

其实我们应用启动的时候会启动Application这个类,这个类是在AndroidManifest.xml文件里其实是默认的

  1. <application  
  2.        android:icon="@drawable/ic_launcher"  
  3.        android:label="@string/app_name"  
  4.        >  
  5.        <activity  
  6.            android:name=".ApplicationDemoActivity"  
  7.            android:label="@string/app_name" >  
  8.            <intent-filter>  
  9.                <action android:name="android.intent.action.MAIN" />  
  10.                <category android:name="android.intent.category.LAUNCHER" />  
  11.            </intent-filter>  
  12.        </activity>  
  13.    </application>  

这个Application类是单例的,也就是说我们可以自己写个Application(比如名为:MainApplication)类,来代替默认的Applicaiton,这个类可以保存应用的全局变量,我们可以定义一个全局的Context.供外部调用.用法如下:

  1. package com.tutor.application;  
  2.   
  3. import android.app.Application;  
  4. import android.content.Context;  
  5.   
  6. public class MainApplication extends Application {  
  7.   
  8.     /** 
  9.      * 全局的上下文. 
  10.      */  
  11.     private static Context mContext;  
  12.       
  13.     @Override  
  14.     public void onCreate() {  
  15.         super.onCreate();  
  16.           
  17.         mContext = getApplicationContext();  
  18.           
  19.     }     
  20.       
  21.     /**获取Context. 
  22.      * @return 
  23.      */  
  24.     public static Context getContext(){  
  25.         return mContext;  
  26.     }  
  27.       
  28.       
  29.     @Override  
  30.     public void onLowMemory() {  
  31.         super.onLowMemory();  
  32.     }  
  33.       
  34.       
  35. }  

我们需要在AndroidMainifest.xml把MainApplication注册进去(第10行代码):

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas./apk/res/android"  
  3.     package="com.tutor.application"  
  4.     android:versionCode="1"  
  5.     android:versionName="1.0" >  
  6.       
  7.     <application  
  8.         android:icon="@drawable/ic_launcher"  
  9.         android:label="@string/app_name"  
  10.         android:name=".MainApplication" >  
  11.         <activity  
  12.             android:name=".ApplicationDemoActivity"  
  13.             android:label="@string/app_name" >  
  14.             <intent-filter>  
  15.                 <action android:name="android.intent.action.MAIN" />  
  16.                 <category android:name="android.intent.category.LAUNCHER" />  
  17.             </intent-filter>  
  18.         </activity>  
  19.     </application>  
  20.       
  21. </manifest>  

为了让大家更容易理解,写了一个简单的Demo.步骤如下:

第一步:新建一个Android工程ApplicationDemo,目录结构如下:


第二步:新建MainApplication.java,代码和上面一样我就不贴了.

第三步:新建一个工具类ToolsUtil.java,代码如下

  1. package com.tutor.application;  
  2.   
  3. import android.content.Context;  
  4. import android.widget.Toast;  
  5.   
  6. /** 
  7.  * @author frankiewei. 
  8.  * 应用的一些工具类. 
  9.  */  
  10. public class ToolUtils {  
  11.       
  12.     /** 
  13.      * 参数带Context. 
  14.      * @param context 
  15.      * @param msg 
  16.      */  
  17.     public static void showToast(Context context,String msg){  
  18.         Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();  
  19.     }  
  20.       
  21.     /** 
  22.      * 调用全局的Context. 
  23.      * @param msg 
  24.      */  
  25.     public static void showToast(String msg){  
  26.         Toast.makeText(MainApplication.getContext(), msg, Toast.LENGTH_SHORT).show();  
  27.     }  
  28. }  

第四步:新建一个View命名为MainView.java就是我们Activity现实的View.代码如下:

  1. package com.tutor.application;  
  2.   
  3. import android.app.Activity;  
  4. import android.content.Context;  
  5. import android.util.AttributeSet;  
  6. import android.view.LayoutInflater;  
  7. import android.view.View;  
  8. import android.widget.Button;  
  9. import android.widget.FrameLayout;  
  10.   
  11. /** 
  12.  * @author frankiewei. 
  13.  * 自定义的MainView. 
  14.  */  
  15. public class MainView extends FrameLayout implements View.OnClickListener{  
  16.       
  17.     private Context mContext;  
  18.       
  19.     private Activity mActivity;  
  20.       
  21.     /** 
  22.      * 参数Button. 
  23.      */  
  24.     private Button mArgButton;  
  25.       
  26.     /** 
  27.      * 全局Button. 
  28.      */  
  29.     private Button mGlobleButton;  
  30.       
  31.     /** 
  32.      * 退出Button. 
  33.      */  
  34.     private Button mExitButton;  
  35.       
  36.     public MainView(Context context){  
  37.         super(context);  
  38.         setupViews();  
  39.     }  
  40.   
  41.     public MainView(Context context, AttributeSet attrs) {  
  42.         super(context, attrs);  
  43.         setupViews();  
  44.     }  
  45.       
  46.       
  47.     private void setupViews(){  
  48.         //获取View的上下文.  
  49.         mContext = getContext();  
  50.         //这里将Context转换为Activity.  
  51.         mActivity = (Activity)mContext;  
  52.         LayoutInflater inflater = LayoutInflater.from(mContext);  
  53.         View v = inflater.inflate(R.layout.main, null);  
  54.         addView(v);  
  55.           
  56.         mArgButton = (Button)v.findViewById(R.id.arg_button);  
  57.         mGlobleButton = (Button)v.findViewById(R.id.glo_button);  
  58.         mExitButton = (Button)v.findViewById(R.id.exit_button);  
  59.           
  60.         mArgButton.setOnClickListener(this);  
  61.         mGlobleButton.setOnClickListener(this);  
  62.         mExitButton.setOnClickListener(this);  
  63.     }  
  64.   
  65.     public void onClick(View v) {  
  66.         if(v == mArgButton){  
  67.             ToolUtils.showToast(mContext, "我是通过传递Context参数显示的!");  
  68.         }else if(v == mGlobleButton){  
  69.             ToolUtils.showToast("我是通过全局Context显示的!");  
  70.         }else{  
  71.             mActivity.finish();  
  72.         }  
  73.     }  
  74.   
  75. }  
这里MainView.java使用的布局main.xml代码如下:

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas./apk/res/android"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent"  
  5.     android:orientation="vertical" >  
  6.   
  7.     <TextView  
  8.         android:layout_width="fill_parent"  
  9.         android:layout_height="wrap_content"  
  10.         android:text="Welcome to frankie wei's blog."   
  11.         />  
  12.       
  13.     <Button  
  14.         android:id="@+id/arg_button"  
  15.         android:layout_width="fill_parent"  
  16.         android:layout_height="wrap_content"  
  17.         android:text="传递Context参数"  
  18.         />  
  19.       
  20.     <Button  
  21.         android:id="@+id/glo_button"  
  22.         android:layout_width="fill_parent"  
  23.         android:layout_height="wrap_content"  
  24.         android:text="全局的Context"  
  25.         />  
  26.       
  27.     <Button  
  28.         android:id="@+id/exit_button"  
  29.         android:layout_width="fill_parent"  
  30.         android:layout_height="wrap_content"  
  31.         android:text="退出App"  
  32.         />  
  33.   
  34. </LinearLayout>  

第五步:修改ApplicationDemoActivity.java,代码如下:

  1. package com.tutor.application;  
  2.   
  3. import android.app.Activity;  
  4. import android.os.Bundle;  
  5.   
  6. public class ApplicationDemoActivity extends Activity {  
  7.     @Override  
  8.     public void onCreate(Bundle savedInstanceState) {  
  9.         super.onCreate(savedInstanceState);  
  10.           
  11.         MainView mMainView = new MainView(this);  
  12.         setContentView(mMainView);  
  13.      
  14.     }  
  15.       
  16. }  

第六步:运行上述工程效果如下:

    

运行效果1                                                            运行效果2---- 点击第一个按钮


 运行效果3---- 点击第二个按钮

好了今天就讲到这里,大家对Context有什么疑问的,可以留言!!!

源代码点击进入==>

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多