Android擷取LayoutInflater對象的方法總結

來源:互聯網
上載者:User

在寫Android程式時,有時候會編寫自訂的View,使用Inflater對象來將布局檔案解析成一個View。本文主要目的是總結擷取LayoutInflater對象的方法。


1、若能擷取context對象,可以有以下幾種方法:

LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);View child = inflater.inflate(R.layout.child, null);

or

LayoutInflater inflater = LayoutInflater.from(context);View child = inflater.inflate(R.layout.child, null);

2、在一個Activity中,可以有以下方法:

View child = getLayoutInflater().inflate(R.layout.child, item, false);
or

View view; LayoutInflater inflater = (LayoutInflater)   getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = inflater.inflate(R.layout.mylayout, null);

方法1和方法2其實都是對context().getSystemService()的使用


3、使用View的靜態方法:

View view=View.inflate(context, R.layout.child, null)

inflate實現源碼如下:

    /**     * Inflate a view from an XML resource.  This convenience method wraps the {@link     * LayoutInflater} class, which provides a full range of options for view inflation.     *     * @param context The Context object for your activity or application.     * @param resource The resource ID to inflate     * @param root A view group that will be the parent.  Used to properly inflate the     * layout_* parameters.     * @see LayoutInflater     */    public static View inflate(Context context, int resource, ViewGroup root) {        LayoutInflater factory = LayoutInflater.from(context);        return factory.inflate(resource, root);    }
LayoutInflater.from(context)實際上是對方法1的封裝,可參考以下源碼:

    /**     * Obtains the LayoutInflater from the given 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;    }




聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.