写在前面:
大部分内容参考该篇文章:Android LayoutInflater原理分析,带你一步步深入了解View(一)
LayoutInflater的基本使用方法
- 首先获取LayoutInflater实例
LayoutInflater inflater = LayoutInflater.from(this); - 调用LayoutInflater实例的inflate()方法加载布局
View button_layout = inflater.inflate(R.layout.button_layout, null); - 通过addView方法将该布局对应的View添加到相应的父View中
mainLayout.addView(button_layout);
下面通过一个完整例子演示下
- MainActivity.java
public class MainActivity extends AppCompatActivity {
private LinearLayout mainLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainLayout = (LinearLayout) this.findViewById(R.id.main_layout);
//1.首先获取LayoutInflater实例
LayoutInflater inflater = LayoutInflater.from(this);
//2.调用LayoutInflater实例的inflate()方法加载布局
View button_layout = inflater.inflate(R.layout.button_layout, null);
//3.通过addView方法将该布局对应的View添加到相应的父View中
mainLayout.addView(button_layout);
}
}
- activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</LinearLayout>
- button_layout.xml
<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" >
</Button>