findViewById(R.id.xxxx),把xml里面的控件根据id绑定到类成员变量,适用于普通控件和布局
LayoutInflater,用于把布局xml里面的东西实例化(会重新实例化,和findViewById不同),sample代码如下
LayoutInflater inflator = getLayoutInflater();
//注意,这里参数是layout,不是id
RelativeLayout layout = (RelativeLayout)inflator.inflate(R.layout.activity_main, null);
TextView aTextView = new TextView(this);
aTextView.setWidth(100);
aTextView.setHeight(100);
aTextView.setText("asdasdasdasd");
layout.addView(aTextView);
//采用LayoutInflater的需要重新设置布局才有效果。
setContentView(layout);
附三种使用LayoutInflater的方法
LayoutInflater inflater = LayoutInflater.from(this);
View layout = inflater.inflate(R.layout.main, null);
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.main, null);
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.main, null);