LayoutInflater佈局管理器

LayoutInflater做用是將layout的xml佈局文件實例化爲View類對象。網絡

實現LayoutInflater的實例化共有3種方法,函數

(1).經過SystemService得到佈局

    LayoutInflater inflater = (LayoutInflater)context.getSystemServices(Context.LAYOUT_INFLATER_SERVICES);spa

    View view = inflater.inflate(R.layout.main, null);orm

(2).從給定的context中得到xml

    LayoutInflater inflater = LayoutInflater.from(context);對象

    View view = inflater.inflate(R.layout.mian, null);資源

(3).get

    LayoutInflater inflater =getLayoutInflater();(在Activity中能夠使用,其實是View子類下window的一個函數)源碼

    View layout = inflater.inflate(R.layout.main, null);

 


其實,這三種方式本質是相同的,從源碼中能夠看出:

getLayoutInflater():

Activity的getLayoutInflater()方法是調用PhoneWindow的getLayoutInflater()方法,看一下該源代碼:

    public PhoneWindow(Context context) {

        super(context);

        mLayoutInflater = LayoutInflater.from(context);

    }

能夠看出它實際上是調用LayoutInflater.from(context)。

LayoutInflater.from(context):

    public static LayoutInflater from(Context context) {

        LayoutInflater LayoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        if(LayoutInflater == null){

            throw new AssertionError("LayoutInflater not found.");

        }

        return LayoutInflater;

    }

能夠看出它其實調用context.getSystemService()。

 

 

public View inflate(int Resourece,View Grouproot)
做用:填充一個新的視圖層次結構從指定的XML資源文件中
reSource:View的layout的ID
root: 生成的層次結構的根視圖
return 填充的層次結構的根視圖。若是參數root提供了,那麼root就是根視圖;不然填充的XML文件的根就是根視圖。

其他幾個重載的inflate函數相似。

另外補充下,getSystemService是Activity中的方法,根據傳入的name來取得對應的服務對象,這些服務名稱參數都是Context類中的常量:

傳入的Name                                                 返回的對象                          說明WINDOW_SERVICE                                 WindowManager           管理打開的窗口程序LAYOUT_INFLATER_SERVICE               LayoutInflater                取得xml裏定義的viewACTIVITY_SERVICE                                ActivityManager             管理應用程序的系統狀態POWER_SERVICE                                   PowerManger                電源的服務ALARM_SERVICE                                    AlarmManager               鬧鐘的服務NOTIFICATION_SERVICE                       NotificationManager       狀態欄的服務KEYGUARD_SERVICE                            KeyguardManager          鍵盤鎖的服務LOCATION_SERVICE                              LocationManager           位置的服務,如GPSSEARCH_SERVICE                                 SearchManager              搜索的服務VEBRATOR_SERVICE                             Vebrator                        手機震動的服務CONNECTIVITY_SERVICE                      Connectivity                   網絡鏈接的服務WIFI_SERVICE                                         WifiManager                   Wi-Fi服務TELEPHONY_SERVICE                          TeleponyManager          電話服務

相關文章
相關標籤/搜索