总是见到LayoutInflater,那么这个东西是干什么的呢?以前没注意,直到今天突然遇到一个问题:
我要用到一个View,就比如说一个设计好的对话框,我要经常用,而且界面的布局是固定的。那么如果我在创建的时候用代码来实现布局的话,可以是可以,但是是多么的麻烦啊!于是我想到,能不能直接在xml布局文件中先布局好,然后直接把这个xml通过某种方式直接放到这个iew上呢?
正在我不知所错的时候,我看到了layoutinflater,然后看到这个东西是给view打气的,也就是把一个xml实例化成一个view。哈哈终于找到解决上述问题的方法了。那么我们下面具体来探讨一下:
首先讲一下layoutinflater的获取方法:
有三种方式:
LayoutInflater.from(this)
getLayoutInflater()
(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE)
以上三种方法都能获得LayoutInflater
对于这个对象,我们只需要深入的探讨一下他的一个方法就可以了,那就是inflate
我们主要研究是的其中的两个
一个是inflate(int id,View parent)
这个方法是通过layout的id来膨胀那个父View。如果parent不是null的话,就返回父View,如果是null的话,就返回撑起的那个VIew
另一个是inflate(int id,View parent,boolean attach)
这个方法是和上面是差不多的,只不过这个时候还要看attach,如果是false,就返回子VIew,否则,返回这个View,你会发现子View被加到了父VIew上
private TextView tv;
private View view;
private View view2;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout3);
/**
* 取得整个layout
*/
LinearLayout ll = (LinearLayout)findViewById(R.id.l3);
LayoutInflater inflater = LayoutInflater.from(this);
//LayoutInflater inflater2 = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.layout4,ll,false);
view2 = inflater.inflate(R.layout.layout2,ll,false);
ll.addView(view);
ll.addView(view2);
Button btn = new Button(this);
btn.setText("gone");
ll.addView(btn);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
MainActivity.this.view.setVisibility(View.GONE);
MainActivity.this.view.setBackgroundColor(Color.RED);
}
});
}