編輯:關於 Android 程式設計
大家好,今天想和大家聊聊 Android 裡 Context 的幾種用法。以前常有朋友在群組裡問我:如果在某個工具類的方法裡,或者在 View 當中需要使用 Context,可是手邊偏偏沒有這個上下文該怎麼辦?為了替大家解惑,我特別寫了一個簡單的 Demo,示範如何得心應手地取得 Context——讓你什麼時候想要,什麼時候就有。
大致可以分成兩種做法:一是透傳 Context 參數,二是呼叫全域的 Context。
其實在我們的應用啟動時,系統會啟動 Application 這個類,它在 AndroidManifest.xml 裡是預設存在的:
<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 android:name="androidintentcategoryLAUNCHER" /> </intent-filter> </activity> </application>
這個 Application 類是單例的,也就是說我們可以自己寫一個 Application(例如命名為 MainApplication)來取代預設的 Application。這個類可以用來保存應用的全域變數,我們就能在其中定義一個全域的 Context 供外部呼叫,用法如下:
package com.tutor.application; import androidappApplication; import androidcontentContext; public class MainApplication extends Application { /** * 全局的上下文 */ private static Context mContext; @Override public void onCreate() { superonCreate(); mContext = getApplicationContext(); } /**獲取Context * @return */ public static Context getContext(){ return mContext; } @Override public void onLowMemory() { superonLowMemory(); } } 接著需要在 AndroidManifest.xml 裡把 MainApplication 註冊進去(見第 10 行程式碼):
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="https://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>
為了讓大家更容易理解,我寫了一個簡單的 Demo,步驟如下:
第一步:新建一個 Android 工程 ApplicationDemo,目錄結構如下:

第二步:新建 MainApplication.java,程式碼與上面相同,這裡就不再重複貼上。
第三步:新建一個工具類 ToolUtils.java,程式碼如下:
package com.tutor.application; import androidcontentContext; import androidwidgetToast; /** * @author frankiewei * 應用的一些工具類 */ public class ToolUtils { /** * 參數帶Context * @param context * @param msg */ public static void showToast(Context context,String msg){ ToastmakeText(context, msg, ToastLENGTH_SHORT)show(); } /** * 調用全局的Context * @param msg */ public static void showToast(String msg){ ToastmakeText(MainApplicationgetContext(), msg, ToastLENGTH_SHORT)show(); } } 第四步:新建一個命名為 MainView.java 的自定義 View,也就是 Activity 要呈現的畫面,程式碼如下:
package com.tutor.application; import androidappActivity; import androidcontentContext; import androidutilAttributeSet; import androidviewLayoutInflater; import androidviewView; import androidwidgetButton; import androidwidgetFrameLayout; /** * @author frankiewei * 自定義的MainView */ public class MainView extends FrameLayout implements ViewOnClickListener{ private Context mContext; private Activity mActivity; /** * 參數Button */ private Button mArgButton; /** * 全局Button */ private Button mGlobleButton; /** * 退出Button */ private Button mExitButton; public MainView(Context context){ super(context); setupViews(); } public MainView(Context context, AttributeSet attrs) { super(context, attrs); setupViews(); } private void setupViews(){ //獲取View的上下文 mContext = getContext(); //這裡將Context轉換為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); } public void onClick(View v) { if(v == mArgButton){ ToolUtilsshowToast(mContext, "我是通過傳遞Context參數顯示的!"); }else if(v == mGlobleButton){ ToolUtilsshowToast("我是通過全局Context顯示的!"); }else{ mActivityfinish(); } } MainView.java 所使用的佈局檔 main.xml 如下:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://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_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="傳遞Context參數" /> <Button android:id="@+id/glo_button" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="全局的Context" /> <Button android:id="@+id/exit_button" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="退出App" /> </LinearLayout>
第五步:修改 ApplicationDemoActivity.java,程式碼如下:
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); } } 第六步:執行上述工程,效果如下:

運行效果一

運行效果二——點擊第一個按鈕

運行效果三——點擊第二個按鈕
以上就是本文的全部內容,希望對大家的學習有所幫助,也歡迎大家多多支持本站。
在 Android Framework 中新增字串與圖片資源
改寫 AOSP 時經常需要讓系統層級的程式也能取用自訂的字串或圖片。這與在 App 專案裡新增資源的關鍵差異在於:framework 資源多了一道 public.xml
Android 框架設計模式(五)—— 單例模式 Singleton
一、單例模式介紹 什麼是單例模式 單例模式指的是在整個全域範圍內(無論單執行緒還是多執行緒),某個物件只存在一個實例,而且只應該存在一個實例,沒有副本(製作副本需要耗費
Android Volley 二次封裝實作:打造可重複使用的網路請求基層
Volley 的定位 Volley 是 Google 推出的網路通訊框架,擅長高頻、小數據量的請求,例如 JSON 介面、列表資料與圖片載入。它不適合大檔案下載。 匯入
Android 多執行緒:Thread、Runnable、Handler、AsyncTask 的關係
Android 的多執行緒其實就是 Java 的多執行緒,而 Android 的 UI 執行緒又稱為主執行緒。以下釐清 Thread、Runnable、Handler、A