我们常常会遇到这样的情况,函数setContentView(R.layout.XXX);指定一个xml文件作为该Activity的布局文件,这样,如果我们要操作该xml文件中的Button、ImageView、TextView等组件,就可以直接用:Button btn = (Button)findViewById(R.id.button);这样是可以的,但是如果我们要操作的这些组件并不在setContentView函数里面指定的xml文件中,这个时候再用上面的方法就会报空指针错误。所以我们要用到inflater
LayoutInflater的作用是将layout文件下的xml文件实例化为View对象,即调用inflate方法将xml文件转成View。
获取LayoutInflater的方法有如下三种:
LayoutInflater inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View layout = inflater.inflate(R.layout.main, null); LayoutInflater inflater = LayoutInflater.from(context); View layout = inflater.inflate(R.layout.main, null); LayoutInflater inflater = getLayoutInflater(); View layout = inflater.inflate(R.layout.main, null);
查看第二种方法的源码,实质上和第一种是一样。
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; }
相关推荐
本文主要介绍Android 中Inflate 方法的用法, 在开发Android应用过程中,可以在程序中应用 Inflate()方法加载新布局,希望能帮助有需要的朋友
Android LayoutInflater.inflate()详解 深入理解LayoutInflater.inflate() 由于我们很容易习惯公式化的预置代码,有时我们会忽略很优雅的细节。LayoutInflater以及它在Fragment的onCreateView()中填充View的方式...
android inflate demo,方便新手使用,下载导入android studio就可直接运行,简单明了的展现inflate不同参数的区别
Android 中LayoutInflater.inflate()方法的介绍 最近一直想弄明白LayoutInflater对象的inflate方法的用法,今天做了实例。 <LinearLayout android:id=@+id/ll_item_Group android:layout_width=match_parent ...
这个demo主要实现了inflate的使用,希望可以帮助需要的同学.
博客《ListView滑动删除实现之一——merge标签与LayoutInflater.inflate()》对应源码,博客地址:http://blog.csdn.net/harvic880925/article/details/45155965
帮助你更好的理解LayoutInflate中的inflate方法,以后想怎么用怎么用
主要介绍了Android LayoutInflater.inflate源码分析的相关资料,需要的朋友可以参考下
Android getViewById和getLayoutInflater().inflate()的详解及比较 由于本人刚刚学习Android 对于getViewById和getLayoutInflater().inflate()的方法该如何使用不知如何分别,这里就上网查下资料整理下,大家可以...
LayoutInflater.from(context).inflate()方法的调研
View contentView = inflater.inflate(R.layout.layout_pop, null); NewFloatMainWindow.getFloatMainWindow(MainActivity.this, NewFloatMainWindow.LOCATION_LEFT, contentView); 3.实现悬浮窗如此简单 readme-...
本文实例讲述了Android开发中setContentView和inflate的区别。分享给大家供大家参考,具体如下: 一般用LayoutInflater做一件事:inflate inflate这个方法总共有四种形式(见下面),目的都是把xml表述的layout转化...
View v = inflater.inflate(R.layout.main, null); addView(v); mArgButton = (Button)v.findViewById(R.id.arg_button); mGlobleButton = (Button)v.findViewById(R.id.glo_button); mExitButton = ...
Android 实现各个方向的气泡弹窗,可控制气泡尖角偏移量。 截图 依赖 dependencies { compile 'com.yuyh.bubble:library:1.0.0' } 使用 默认弹窗BubblePopupWindow leftTopWindow = new BubblePopupWindow...
import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.app.Activity; import android.content.Intent; import android.view.Menu; import android.webkit.WebView; ...
Inflate有三个参数,我在初学Android的时候这么理解的: (1)对于Inflate的三个参数(int resource, ViewGroup root, boolean attachToRoot); (2)如果inflate(layoutId, null )则layoutId的最外层的控件的宽高是...