LayoutInflater的动态增加控件

  在实际开发中LayoutInflater这个类是非常有用的,它的作用类似于 findViewById(),不同点是LayoutInflater是用来找layout下xml布局文件。

而findViewById()是查找的具体 widget控件(如Button,TextView等)。

1.main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/vertical_container" 
    android:orientation="vertical"
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent">
</LinearLayout>

2.dynamic_add.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="25dip" 
    android:layout_height="25dip"
    android:background="#ff0000" 
    android:text="dynamic_add" />

3.activity

    private View view;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);
        ViewGroup parent = (ViewGroup) findViewById(R.id.vertical_container);

        // result: layout_height=wrap_content layout_width=match_parent
        //inflate(int resource, ViewGroup root)
        //inflate 返回root view,如果提供root参数则返回root,否则返回resource的root
        view = LayoutInflater.from(getBaseContext())
                                        .inflate(R.layout.dynamic_add,null);
        parent.addView(view);

        // result: layout_height=100 layout_width=100
        view = LayoutInflater.from(getBaseContext())
                                        .inflate(R.layout.dynamic_add,null);
        parent.addView(view, 100, 100);

        // result: layout_height=25dip layout_width=25dip
        view = LayoutInflater.from(getBaseContext())
                                         .inflate(R.layout.dynamic_add,parent, false);
        parent.addView(view);

        // result: layout_height=25dip layout_width=25dip 
        // parent.addView(view) not necessary as this is already done by attachRoot=true
        view = LayoutInflater.from(getBaseContext())
                                        .inflate(R.layout.dynamic_add,parent, true);
    }
   在一个Activity里如果直接用findViewById()的话,对应的是setConentView()的那个layout里的组件.如果你的Activity里如果用到别的layout,
比如对话框上的layout,你还要设置对话框上的layout里的组件(ImageView,TextView)上的内容,你就必须用inflate()先将对话框上的layout找出来,
然后再用这个layout对象去找到它上面的组件,如:
View view = View.inflate(this, R.layout.dialog_layout, null);
TextView dialogTV = (TextView) view.findViewById(R.id.dialog_tv);
dialogTV.setText("abcd");
原文地址:https://www.cnblogs.com/yuyutianxia/p/3541743.html