在之前的安卓学习中每次编写程序想必都会用到findViewById(),这个方法,我们都知道它是用来获取某个已经定义好的控件后对其作相应的操作。其实LayoutInflater与findViewById()的作用类似,只不过LayoutInflater不是用来获取控件的,而是用来获取布局对象的。
在大多数的开发过程中,我们前面定义好的布局文件都不能时刻满足我们的实际需求,这句需要我们动态的在代码中改写布局文件,这是就要用到LayoutInflater。LayoutInflater在在网上查找LayoutInflater,在安卓中是扩展的意思。其最常用的地方是在BaseAdapter的getView方法中,,用来获取整个View并返回。
下面就是其中一个例子:
下面就是其中一个例子:
private class MyAdapter extends ArrayAdapter<Contact> {
private int resource;
private LayoutInflater inflater = null;
private ArrayList<Contact> contacts;
private LayoutInflater inflater = null;
private ArrayList<Contact> contacts;
public MyAdapter(Context context, int resource,
ArrayList<Contact> contacts) {
super(context, resource);
this.resource = resource;
this.contacts = contacts;
ArrayList<Contact> contacts) {
super(context, resource);
this.resource = resource;
this.contacts = contacts;
inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null)
convertView = inflater.inflate(resource, null);
convertView = inflater.inflate(resource, null);
Contact c = getItem(position);
TextView text1 = (TextView) convertView
.findViewById(android.R.id.text1);
TextView text2 = (TextView) convertView
.findViewById(android.R.id.text2);
.findViewById(android.R.id.text1);
TextView text2 = (TextView) convertView
.findViewById(android.R.id.text2);
//首字符,分组的依据。
text1.setText(c.firstLetterOfName());
//详情。
text2.setText(c.name + " " + c.getPhoneNumbers());
text1.setText(c.firstLetterOfName());
//详情。
text2.setText(c.name + " " + c.getPhoneNumbers());
return convertView;
}
}
LayputInflater的用法有三种:
1:
LayoutInflater inflater = LayoutInflater.from(this);
View layout = inflater.inflate(R.layout.main, null);
View layout = inflater.inflate(R.layout.main, null);
2:
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.main, null);
View layout = inflater.inflate(R.layout.main, null);
3:
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.main, null);
View layout = inflater.inflate(R.layout.main, null);
那LayoutInflater的inflate(int resource,ViewGroupr root,boolean attachToRoot)方法的三个参数的含义是什么呢?
resource:是需要加载的布局文件的ID,
root:如果第三个参数为true,那就是你实例化的view为root的子view
attachToRoot:自然解决
若只是单纯获得布局文件对其进行操作,可写成View layout = inflater.inflate(R.layout.main, null);的形式。