`
ableouou
  • 浏览: 72555 次
  • 性别: Icon_minigender_2
  • 来自: 深圳
文章分类
社区版块
存档分类
最新评论

Inflate方法

阅读更多
inflate方法总共有四种形式,把xml表达的layout转化为view. This class is used to instantiate layout xml files into its corresponding view object. It is never be used directly——use getLayoutInflater() or getSystemService(String)getLayoutInflate() or getSystemService(String) to retrieve a standard LayoutInflater instance that is already hooked up that is already hook up to the current context and correct configured for the device you are running on.
1. Context.public abstract object getSystemService(String name)
2. 两种获得LayoutInflater的方法
a. 通过SystemService获得
LayoutInflater inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLEATER_SERVICE);
b. 从给定的context中获取
Public static LayoutInflater from(Context context)
c. 两者的区别:实际上是一样的,源码
/**
     * 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;
}
3. LayoutInflater.inflate()将Layout文件转换为View,专门供Layout使用的Inflater。虽然Layout也是View的子类,但在android中如果想将xml中的Layout转换为View放入.java代码中操作,只能通过Inflater,而不能通过findViewById()。
4. LinearLayout linearLayout =
(LinearLayout) findViewById(R.id.placeslist_linearlayout);
linearLayout.addView(place_type_text);
5. findViewById有两种形式
R.layout.xx是引用res/layout/xx.xml的布局文件(inflate 方法),R.id.xx是引用布局文件里面的组件,组件的id是xx(findViewById方法)。所有的组件id都能用R.id.xx来查看,但是组件不在setContentView()里面的layout中就无法使用,Activity.findViewById()会出现空指针异常
a. activity中的findViewById(int id)
b. View 中的findViewById(int id)
6.不同点是LayoutInflater是用来找layout下xml布局文件,并且实例化!而findViewById()是找具体xml下的具体 widget控件(如:Button,TextView等)。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics