android 中 setContentView() 的前世今生

新建一个android项目时, 初始化activity时,总能看到到setContentView(R.layout.main);这行代码,以前只知道这行代码能把main布局文件的内容布局加载并显示出来,但是加载的过程并不是十分清楚,今天经过查询资料,对他的实现过程总结一下,自己学习的同时也希望能帮助有相同疑惑的同仁们。

android的编写与java有着莫大的渊源,我们从java一路走来,习惯于任何对象都是new出来,android与java一脉相承,那么在这里面我们需要的对象可以自己new吗?

回答是肯定的,下面的控件都是通过硬编码new出所需的控件,

 LayoutParams params=new LayoutParams(0,LayoutParams.WRAP_CONTENT, 1.0f);//注意是那个布局的布局参数,如线性布局
       
       TextView tvUserName=new TextView(this);
       tvUserName.setText("用户名");
       EditText etUserName=new EditText(this);
       etUserName.setHint("请输入用户名");
       etUserName.setLayoutParams(params);//设置布局参数
       LinearLayout row1=new LinearLayout(this);
       row1.addView(tvUserName);
       row1.addView(etUserName);
       
       TextView tvPassword=new TextView(this);
       tvPassword.setText("密	码");
       EditText etPassword=new EditText(this);
       etPassword.setHint("请输入密码");
       LinearLayout row2=new LinearLayout(this);
       row2.addView(tvPassword);
       row2.addView(etPassword,params);
       
       
       Button btnLogin=new Button(this);
       btnLogin.setText("登陆");
       Button btnCancle=new Button(this);
       btnCancle.setText("取消");
       LinearLayout row3=new LinearLayout(this);
       row3.addView(btnLogin,params);
       row3.addView(btnCancle,params);
       
       LinearLayout root=new LinearLayout(this);
       root.setOrientation(LinearLayout.VERTICAL);
       root.addView(row1);
       root.addView(row2);
       root.addView(row3);
       this.setContentView(root);
我们并把多有的组件组成视图,然后单击运行,出现下面的界面:
这说明采用硬编码的方式完全可以实现将布局文件文件显示出来,但是采用这种方式显示,需要书写大量的代码,增加程序员的负担,因此,android把布局放到xml文件中,
作为资源的一部分,通过LayoutInflater这个类将xml布局文件加载并显示成对应视图。解析xml文件需要用到的方法有LayoutInflater的静态方法from来获取一个LayoutInflater实例inflater,再通过inflater的inflate方法返回一个视图实例,最后通过setContentView的方法把这个视图实例加载出来。实现的代码如下:
对应的xml文件:



    

        

        
    

    

        

        
    

    

        

activity中用到的相关代码:



	LayoutInflater inflater=LayoutInflater.from(this);
   	LinearLayout root= (LinearLayout) inflater.inflate(R.layout.main, null);
   this.setContentView(root);
LayoutInflater这个类一般用在非activity中设置相应的视图;

你可能感兴趣的:(android 中 setContentView() 的前世今生)