在实际开发中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); }
View view = View.inflate(this, R.layout.dialog_layout, null); TextView dialogTV = (TextView) view.findViewById(R.id.dialog_tv); dialogTV.setText("abcd");
原文:http://www.cnblogs.com/yuyutianxia/p/3541743.html