加载view有两种方式,setContentView和inflate。 LayoutInflate,inflate加载xml资源文件。 Activity,setContentView,可以加载xml,也可以加载View对象方式。 重载方法有 public void setContentView(int layoutResID);//重载1 public void setContentView(View view); //重载2 public void setContentView(View view, ViewGroup.LayoutParams params);//重载3 这里着重介绍一下带源代码(非xml配置文件)中动态加载view的方式。 动态加载,需要设置布局参数,即告诉要加载view的parent一些它期望的宽、高、位置等信息,即需要设置LayoutParam参数(ViewGroup.LayoutParams及其它的子类)。具体有ViewGroup.MarginLayoutParams,LinearLayout.LayoutParams,… View的方法public void setLayoutParams(ViewGroup.LayoutParams params), 即可以设置布局参数,以在parent add时设置布局。如果设置了View. setLayoutParams,则使用重载2添加;如果没有设置,则new一个LayoutParams对象,使用重载3添加。看下面的例子,
mLayout = new LinearLayout(this); mLayout.setLayoutParams(new LinearLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); mLayout.setOrientation(LinearLayout.VERTICAL); mTv = new TextView(this); mTv.setText("Hello code1"); mTv.setTextSize(19); LayoutParams params = new LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); mLayout.addView(mTv, params); setContentView(mLayout);