inflate与setcontentview及findviewbyid(1)

inflate与setcontentview及findviewbyid(一)



 LayoutInflater layoutInflater=LayoutInflater.from(MainActivity.this);
View view=    layoutInflater.inflate(R.layout.g, null);
        Button button =(Button)  LayoutInflater.from(getApplicationContext()).inflate(R.layout.g,null,false).findViewById(R.id.button1);
  // Button button=(Button)view.findViewById(R.id.button1);
     //   Button button=(Button)findViewById(R.id.button1);
      setContentView(view);
此时Button也没有作用 第一次View view的时候inflate了一次,第二次找Button的时候又inflate一次,button是属于第二次inflate的,而最终setcontentview却传的是第一次inflate的,所以,button实际上没有加载进来,因为button是第二次inflate的


正确的写法为:
 LayoutInflater layoutInflater=LayoutInflater.from(MainActivity.this);
View view=    layoutInflater.inflate(R.layout.g, null);
Button button=(Button)view.findViewById(R.id.button1);
setContentView(view);


inf late,根据每个xml布局文件翻译成相当于JavaBEAN的Java类,其中的每个属性,相当于XML中的每个节点,如此,实例每个节点的对象,每个节点的唯一值就是ID属性

findviewbyid,根据ID找到已经生成的对象,所以,严格来说,findviewbyid和new是不同的,每new一次,就会有一个对象,findviewbyid则只找到对象的对象

版权声明:本文为博主原创文章,未经博主允许不得转载。